Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Write text file in C programming

Tags:

c

file

text

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.

like image 996
geyan Avatar asked Jan 19 '23 00:01

geyan


2 Answers

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.

like image 172
Vinayak Garg Avatar answered Jan 24 '23 21:01

Vinayak Garg


You need to seek back to the beginning of the file after you write to it and before you start reading:

fseek(inFile, 0, SEEK_SET);
like image 44
Adam Zalcman Avatar answered Jan 24 '23 23:01

Adam Zalcman