gpt4 book ai didi

C 编程 如何从文本文件中获取特定行的字符串?

转载 作者:行者123 更新时间:2023-11-30 19:47:35 26 4
gpt4 key购买 nike

我的任务是创建一个输入数字的程序,然后该程序将打开一个文件并检索给定句子中的字符串。这是我正在使用的文本文件。

billy
bob
james
peter
mike
kieran
obidiah
scarlett
john
chloe
sarah
bob
leon
david
andrew
james
shawn
hannah
peter
phoebe
chris
john
mark
meg

现在,我认为获取名称、获取计数值并从那里对其进行逆向工程更容易,但是我完全不知道如何做到这一点,有人可以帮忙吗?

   int main(int argc, char *argv[]) {
int count = 1;

char wd[20], word[20];

FILE *fp;

fp = fopen("Names.txt", "r");
if (fp == NULL) {
printf("given file doesn't exist");
getch();
} else {
printf("Name: ");
scanf("%s", word);
fscanf(fp, "%s", wd);
while (!feof(fp)) {
if (strcmp(word, wd) == 0) {
printf("%s found in the file. the given word is the %d word in the file", word, count);
count = 0;
break;
} else {
fscanf(fp, "%s", wd);
count++;
}
}
if (count != 0) {
printf("given word is not found in the file");
}
getch();
}
}

这是行代码的名称,我想要名称代码的计数。

最佳答案

fgets() 从文件中读取一行,因此如果您需要第 n 行(并且您确信您知道文件中一行的最大长度),只需调用 fgets() n 次。您认为更简单的方法并不容易,并且似乎无法解决所请求的任务。

从命令行读取行号,这样不太符合你作业的规范,这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_BUFFER_SIZE 1024


/* Parse the command line arguments */

int parse_cmd_line(int argc, char *argv[]) {

/* Check we have a single argument */

if ( argc != 2 ) {
printf("You must enter a single integral argument.\n");
exit(EXIT_FAILURE);
}


/* Check that argument is an integer greater than zero */

char * endptr;
int fline = strtol(argv[1], &endptr, 10);
if ( *endptr || fline < 1 ) {
printf("You must enter a positive non-zero integral argument.\n");
exit(EXIT_FAILURE);
}

return fline;
}


/* Trim trailing whitespace from a string */

char * trim_trailing(char * buffer) {
int idx = strlen(buffer) - 1;
while ( idx >= 0 && isspace(buffer[idx]) ) {
buffer[idx--] = 0;
}
return buffer;
}


/* Main function */

int main(int argc, char *argv[]) {
int fline = parse_cmd_line(argc, argv);

FILE * infile = fopen("data.txt", "r");
if ( !infile ) {
perror("Couldn't open data.txt");
exit(EXIT_FAILURE);
}

int count = fline;
char buffer[MAX_BUFFER_SIZE];

while ( count-- > 0 ) {
if ( fgets(buffer, MAX_BUFFER_SIZE, infile) == NULL ) {
printf("There aren't that many lines in the file.\n");
exit(EXIT_FAILURE);
}
}

fclose(infile);

printf("Line %d contains '%s'\n", fline, trim_trailing(buffer));

return EXIT_SUCCESS;
}

将输出您的数据文件:

paul@MacBook:~/Documents/src/scratch$ ./fileline 1
Line 1 contains 'billy'
paul@MacBook:~/Documents/src/scratch$ ./fileline 7
Line 7 contains 'obidiah'
paul@MacBook:~/Documents/src/scratch$ ./fileline 24
Line 24 contains 'meg'
paul@MacBook:~/Documents/src/scratch$ ./fileline 25
There aren't that many lines in the file.
paul@MacBook:~/Documents/src/scratch$

关于C 编程 如何从文本文件中获取特定行的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21405632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com