簡體   English   中英

嘗試從讀取的文件中fprintf某個字符串

[英]Trying to fprintf a certain string from a file read

我正在努力將文件中的字符串打印到新文件中,似乎無法將其纏住,也無法使其正常工作,任何幫助都將非常有用。

該文件如下所示:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM