gpt4 book ai didi

c - 从文件中的特定点读取一行

转载 作者:行者123 更新时间:2023-11-30 14:59:48 24 4
gpt4 key购买 nike

所以我正在编写代码来获取 scanf 文本文件并返回格式文本消息日志。我想知道如何在某个点扫描文件中的字符串并打印该点之外的每个字符串 E.X 当文件扫描该行时“332982000 2055552002 2055551001 7 韦伯先生,我可以问你一个问题吗?”我将前 4 个数字扫描为整数,并将其余的书面文本扫描到从“Mr. Webb”开始的字符数组中。

我尝试使用 for 循环和 fscanf 来扫描数组,但没有成功。我还想我可以使用 malloc 只是为了节省空间,但我不知道在 sizeof 参数中放入什么。任何帮助将不胜感激!

int posix;
int phone1;
int phone2;
int textsize;
int val, val2;
char line[256];
char text[3000];
int len=strlen(line);
int i=0;

printf("\n\nTime %s %s", argv[2], argv[3]);
printf("\n======================================================================================\n\n\n");

FILE* textfile= fopen(argv[1],"r");

fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);

while( fgets(line, sizeof(line), textfile) ) {

val= atoi(argv[2]);
val2=atoi(argv[3]);

if ( (val==phone1) && (val2==phone2) ) {
printf(" %s ", text); //only prints Mr
text=(char*)malloc(sizeof())//tried malloc but not too sure how to use it correctly
for (i=0; i<len; i++) { //tried using for loop here didnt work.
fscanf("%s", text);
}

sortText(phone1, phone2, textsize, text);
//readableTime(posix);
}

else if ( (val2==phone1) && (val==phone2) ) { printf("%s ", 文本);

        sortText(phone1, phone2, textsize, text);
//readableTime(posix);
}


fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);

}

fclose(textfile);
return 0;

}

最佳答案

首先,将整个文件读入 malloc 的字符数组中。 fseek 和 ftell 为您提供文件大小:

// C99
FILE *fp = fopen("file", "r");
size_t filesize;
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *filetext = malloc(filesize + 1);
fread(filetext, 1, filesize, fp);
filetext[filesize] = 0;

然后使用整个文件大小的单行缓冲区,这样您就肯定有足够的大小。 sscanf() 可用于从字符串中读取内容。

int readbytes;

for(int i=0; i < filesize; i+=readbytes) {
char line[filesize];
int posix, phone1, phone2, textsize;

if(EOF == sscanf(
&filetext[i], "%d%d%d%d%[^\n]%n", &posix, &phone1,
&phone2, &textsize, line, &readbytes))
{
break;
}

printf("%d %d %d %d '%s' %d\n", posix, phone1, phone2, textsize, line, readbytes);
}

格式说明符“%[^\n]”表示:直到下一个换行符的每个字符。格式说明符“%n”为您提供迄今为止通过此 sscanf 调用读取的字节数,实际上是您的行大小,您可以使用它来推进迭代器。

关于c - 从文件中的特定点读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519194/

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