gpt4 book ai didi

c - 如何在C文件中跳行?

转载 作者:行者123 更新时间:2023-11-30 17:15:22 25 4
gpt4 key购买 nike

如何在文件中的每一行重复此过程?我正在做的是从文件中读取名称和数字。但我一次只能做一行。因此,我需要跳过几行并在下一行重复该过程,直到到达末尾。

当我这样做时,它只复制第一行。每次读取姓氏时,我都会得到偏移量,因为我需要先获取姓氏,然后将其写在名字之后。所以我需要一个引用来返回到行的开头。我使用了 fseek 并使用了偏移量。但它只适用于 1 行。

一切都可以在 1 行上完成。假设我使用的功能工作正常。有建议吗?

number_of_conversions = fscanf(fp, "%c", &c);
//fseek(fp, -1, SEEK_CUR);
while (number_of_conversions != 0 && number_of_conversions != EOF){
number_of_conversions = fscanf(fp, "%c", &c);
if (c == '\n'){
lines++;
}
}
fseek(fp, 0, SEEK_SET);
offset = ftell(fp);
while (j <= lines){
last_name(fp, string, plength, poffset);
offset = ftell(fp);
first_name(fp, string, plength, poffset);
get_scores(fp, scores);
for (i = 0; i < 20; i++){
fprintf(fp2, "%c", string[i]);
}
for (i = 0; i < 50; i++){
fprintf(fp2, "%c", scores[i]);
}
fprintf(fp2,"\n");
j++;
}

最佳答案

此代码将每一行读取为字符串,您可以对此字符串应用字符串操作。您可以使用自己的子字符串函数来完成该任务。

#include <stdio.h>

int main(int argc, char * argv[])
{
FILE *fptr;
int len;
char str[2000];
fptr = fopen("test.txt","r");
fseek(fptr,0,SEEK_END);
len=ftell(fptr);
rewind(fptr);
while(1)
{
fscanf(fptr,"%[^\n]",&str);
if(str!=NULL)
printf("%s\n",str);
if(ftell(fptr)==len)
break;
fseek(fptr,2,SEEK_CUR);
}
fclose(ftpr);
return 0;
}

关于c - 如何在C文件中跳行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30012015/

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