0

I want to first write something to a file, then use fgets to read it. But I want it to work without close it and switch file open mode between read and write,

I have tried r+ and w+ for file open. For r+ it is able to read original content but fail to read newly inserted content. For w+ it does not read anything I think that's because w+ clear the original content.

I currently found no way to read the newly inserted content of a file before close and switch file open mode, although with fflush new content is already written to a file and can be viewed externally.

Here is a simple code snippet for testing.

#include <stdio.h>

int main()
{
    FILE *fp = NULL;
    char line[256]; 
    int status;

    /*input by user*/
    scanf("%s", line);

    /*write to a file*/
    fp = fopen("f5.txt", "w+");
    fprintf(fp, "%s", line);
    fflush(fp); /*flush buffer*/

    /*read it*/
    char lineRead[256];
    while (fgets(lineRead, 5, fp) != NULL) {
        puts(lineRead);
    }

    fclose(fp);
}
Summer Sun
  • 947
  • 13
  • 33

2 Answers2

2

You might use not only fflush, but also rewind, fseek, ftell (or even fgetpos & fsetpos)

Beware that any standard IO function can fail, and you should check that.

On Linux, some files (e.g. fifo(7)) are not seekable.

Perhaps you want some higher level way of storing persistent data on the disk. Did you consider using some library for indexed files (like gdbm) or for databases (like sqlite)? Or even use a full fledged database, like with some RDBMS (e.g. PostGreSQL or MySQL or MariaDB which are free software), or some NoSQL thing like e.g. MongoDB ?

There is no way to insert a sequence of bytes in the middle of some file or to delete, i.e. remove, a sequence of bytes inside a file. This is a fundamental limitation of file systems on most current operating systems (and on all usual ones like Linux & Windows & Android & MacOSX). You generally should copy that file (by chunks) into some other one (and libraries like gdbm or sqlite don't do that, they either append some data to a file at its end or rewrite some bytes inside the file; they might also truncate a file).

In particular, if you want to programmatically insert some line in the middle of some small text file, you usually should read the file entirely in some appropriate data structure, modify that data structure in memory, then dump that data structure into the (overwritten) file.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thank you Basile, for my problem here is the file position is incoreect. I use rewind after fflush and it works to read from the header of newly inserted content. Thank you for your kind reminds! – Summer Sun Jun 20 '18 at 05:24
1

You need to use fseek() to return to the beginning of the file before trying to read it.

r3mus n0x
  • 5,954
  • 1
  • 13
  • 34