gpt4 book ai didi

c - 尝试从读取的文件中 fprintf 某个字符串

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

我正在努力将字符串从文件打印到新文件,但似乎无法集中注意力也无法让它工作,任何帮助都会很棒。

该文件如下所示:

New York,4:20,3:03Kansas City,12:03,3:00North Bay,16:00,0:20Kapuskasing,10:00,4:02Thunder Bay,0:32,0:31

I am trying to fprintf just the file names to a new file called theCities.txt. The logic makes sense in my head but in terms of implementation, I don't know how I can fprintf a pointer to the string. Any help would be great.

while (fgets(flightInfo[i], 1024, fp) > 0) {
clearTrailingCarraigeReturn(flightInfo[i]);
// display the line we got from the fill
printf(" >>> read record [%s]\n", flightInfo[i]);

char *p = flightInfo[i];
for (;;) {
p = strchr(p, ',');
fp = fopen("theCities.txt", "w+");
fprintf(fp, "%s\n", p);
if (!p)
break;
++p;
}
i++;
}

最佳答案

您处理文件指针的方式有误:

FILE *fpIn, *fpOut;
if (!(fpIn= fopen("yourfile.txt", "r"))) return -1;
if (!(fpOut=fopen("cities.txt", "w"))){fclose(fpIn); return -1;}
while (fgets(flightInfo[i], 1024, fpIn) > 0)
{
clearTrailingCarraigeReturn(flightInfo[i]);
// display the line we got from the fill
printf(" >>> read record [%s]\n", flightInfo[i]);

char *p = flightInfo[i];
for (;;)
{
p = strchr(p, ',');
fprintf(fpOut, "%s\n", p);
if (!p) break;
++p;
}

i++;

}
fclose(fpIn);
fclose(fpOut);

关于c - 尝试从读取的文件中 fprintf 某个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540282/

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