我正在努力将文件中的字符串打印到新文件中,似乎无法绕过它并使其工作,任何帮助都会很棒。
该文件如下所示:
New York,4:20,3:03 Kansas City,12:03,3:00 North Bay,16:00,0:20 Kapuskasing,10:00,4:02 Thunder Bay,0:32,0:31
我正在尝试将fprintf
文件名改为名为theCities.txt的新文件。逻辑在我的头脑中是有道理的,但在实现方面,我不知道如何fprintf
指向字符串的指针。任何帮助都会很棒。
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);
您的代码有问题:
fp
,这非常令人困惑。"%.*s"
输出字符串的一部分而不是行的结尾。这是一个修改版本:
FILE *outp = fopen("theCities.txt", "w");
for (i = 0; fgets(flightInfo[i], 1024, fp) > 0; i++) {
clearTrailingCarraigeReturn(flightInfo[i]);
// display the line we got from the fill
printf(" >>> read record [%s]\n", flightInfo[i]);
int city_length = strcspn(flightInfo[i], ",");
if (city_length) {
fprintf(outp, "%.*s\n", city_length, flightInfo[i]);
}
}
fclose(outp);
为了更新我所做的事情,我使用了@Paul Ogilvie中的方法并对其进行了调整,以便我仍然可以获取文件路径/名称的cmd行参数。然后我使用了strtok而跳过了数字,因此它只将城市名称输出到txt文件。感谢大家的帮助!
FILE *fpIn, *fpOut;
if (!(fpIn = fopen(argv[1], "r"))) return -1;
if (!(fpOut = fopen("theCities.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];
char *n = flightInfo[i];
char *c = flightInfo[i];
while(p != NULL)
{
p = strtok(p, ",");
n = strtok(p, "[1-9]");
c = strtok(p, ":");
if (!p) break;
while (n != NULL && c != NULL)
{
n = strtok(NULL, " ");
c = strtok(NULL, " ");
}
fprintf(fpOut, "%s\n", p);
p++;
p = strtok(NULL, " ");
}
i++;
}
fclose(fpIn);
fclose(fpOut);