ftruncate on file opened with fopen

前端 未结 3 1491
无人及你
无人及你 2021-01-20 20:14

Platform is Ubuntu Linux on ARM. I want to write a string to a file, but I want every time to truncate the file and then write the string, i.e. no append.

I have thi

相关标签:
3条回答
  • 2021-01-20 20:29

    You should not really mix file handle and file descriptor calls like that.

    What's almost certainly happening without the fflush is that the some string is waiting in file handle buffers for delivery to the file descriptor. You then truncate the file descriptor and fclose the file handle, flushing the string, hence it shows up in the file.

    With the fflush, some string is sent to the file descriptor and then you truncate it. With no further flushing, the file stays truncated.

    0 讨论(0)
  • 2021-01-20 20:33

    POSIX requires you to take specific actions (which ensure that no ugly side effects of buffering make your program go haywire) when switching between using a FILE stream and a file descriptor to access the same open file. This is described in XSH 2.5.1 Interaction of File Descriptors and Standard I/O Streams.

    In your case, I believe it should suffice to just call fflush before ftruncate, like you're doing. Omitting this step, per the rules of 2.5.1, results in undefined behavior.

    0 讨论(0)
  • 2021-01-20 20:44

    If you want to literally "truncate the file then write", then it's sufficient to:

    f=fopen("/home/user1/refresh.txt","w");
    fputs("some string",f);
    fclose(f);
    

    Opening the file in the mode w will truncate it (as opposed to mode a which is for appending to the end).

    Also calling fclose will flush the output buffer so no data gets lost.

    0 讨论(0)
提交回复
热议问题