简体   繁体   中英

Read/Write text file in C programming

I need to write something into a txt file and read the contents, then print them on the screen. Below is the code I have written, it can create and write contents into file correctly, but it cannot read from the file and print correctly.

#include<stdio.h>
#include<stdlib.h>
main()
{
    char filename[20]={"c:\\test.txt"};
    FILE *inFile;
    char c;
    inFile=fopen(filename,"w+");

    if(inFile==NULL)
    {
        printf("An error occoured!");
        exit(1);
    }
    while((c=getchar())!=EOF)
        fputc(c,inFile);
    fputc('\0',inFile);

    while((c=fgetc(inFile))!=EOF)
        putchar(c);
}

Would someone tell me what's wrong with this program, especially the last two lines. Thanks in advance.

You need to add

fseek(inFile, 0, SEEK_SET);

before

while ((c=fgetc(inFile)) != EOF)
     putchar(c);

because the file pointer (not the one used for memory allocation) has moved to the end. To read from the file, you have to bring it to the front with the fseek function.

在写入文件之后和开始阅读之前,您需要回到文件的开头:

fseek(inFile, 0, SEEK_SET);
char c;

is your first problem. getc and getchar return int s, not a char s. Read the man page carefully and change that local to:

int c;

You're also not resetting the inFile stream after the writes. Put something like:

fseek(inFile, 0L, SEEK_SET);

before you start reading from that stream. (See the man page.)

Lastly, your main signature is not standard. Use:

int main(void) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM