首页 > 解决方案 > 重置后使用相同的文件指针,但遇到问题

问题描述

我正在学习 C,目前正在处理文件。我正在尝试创建一个从 txt 文件读取的程序,对其进行一些更改,然后将其保存到不同的 txt 文件中。到目前为止,我已经成功编写了程序,它可以从 txt 文件中读取,并对其内容进行更改,并将其保存到不同的文件中。我需要做的最后一件事是打印新 txt 文件的内容,但我遇到了问题。

接下来是程序的最后一部分,事情似乎出了问题。

ifp = fopen(buffer, "r");             //the array "buffer" stores the user input for the file name
rewind(ifp);                          //I have used ifp for reading the file to change, so I have resetted the file position.

while (1)
{
    file_char = fgetc(ifp);
    if (file_char == EOF) break;
    printf("%c", file_char);
}

我尝试调试代码,问题似乎是fgetc(ifp)部分不起作用,导致file_char变为 EOF 并且循环退出。奇怪的是,我使用相同的代码来读取第一个 txt 文件并且它工作得很好,但是做同样的事情导致了这个。

这是完整的代码,可以更好地理解我写的内容。

#include <stdio.h>

int main()
{
    FILE* ifp, *ofp;
    char buffer[20];
    char file_char;

    printf("Input txt file name to change : ");
    scanf("%s", buffer);
    ifp = fopen(buffer, "r");
    while(1)
    {
        file_char = fgetc(ifp);
        if (file_char == EOF) break;
        printf("%c", file_char);
    }
    rewind(ifp);
    printf("Input txt file name to create : ");
    scanf("%s", buffer);
    ofp = fopen(buffer, "w");
    while (1)                                      //Changing contents of file
    {
        file_char = fgetc(ifp);
        if (file_char == EOF) break;
        if (file_char == '\n')
        {
            fprintf(ofp, "%c\n", file_char);
        }
        else
            fprintf(ofp, "%c", file_char);
    }
    ifp = fopen(buffer, "r");
    rewind(ifp);

    while (1)
    {
        file_char = fgetc(ifp);
        if (file_char == EOF) break;
        printf("%c", file_char);
    }
    fclose(ifp);
    fclose(ofp);
    return 0;
}

编辑))为了显示发生了什么,假设我有一个名为a.txt的 txt 文件,其内容为:

stackoverflow
123

那么当程序继续时应该发生的是:

Input txt file name to change : a.txt
stackoverflow
123
Input txt file name to create : b.txt
stackoverflow

123


和 b.txt 正在创建它包含:

stackoverflow

123


但是当我执行程序时,它会:

Input txt file name to change : a.txt
stackoverflow
123
Input txt file name to create : b.txt
 

并且b.txt被成功创建。

标签: c

解决方案


推荐阅读