对使用fopen打开的文件进行ftruncate [英] ftruncate on file opened with fopen
问题描述
平台是ARM上的Ubuntu Linux. 我想向文件中写入一个字符串,但是我想每次都截断该文件,然后写入该字符串,即不附加.
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.
我有此代码:
f=fopen("/home/user1/refresh.txt","w");
fputs( "{"some string",f);
fflush(f);
ftruncate(fileno(f),(off_t)0);
flcose(f);
如果我运行它然后检查文件,它将为零长度,并且在打开时将没有任何内容.
如果我删除fflush
调用,它将不会为0(将为11),而当我打开它时,它将出现某些字符串".
这是正常现象吗?
调用fflush
并没有问题,但是我想循环执行,调用fflush
可能会大大增加执行时间.
If I run it and then check the file, it will be of zero length and when opened, there will be nothing in it.
If I remove the fflush
call, it will NOT be 0 (will be 11) and when I open it there will be "some string" in it.
Is this the normal behavior?
I do not have a problem calling fflush
, but I want to do this in a loop and calling fflush
may increase the execution time considerably.
推荐答案
您不应真正混用这样的文件句柄和文件描述符调用.
You should not really mix file handle and file descriptor calls like that.
几乎可以肯定,没有fflush发生的是some string
在文件句柄缓冲区中等待传递到文件描述符.然后,您截断文件描述符并关闭文件句柄,刷新字符串,从而将其显示在文件中.
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.
使用,将some string
发送到文件描述符,然后然后截断它.在没有进一步刷新的情况下,文件保持被截断的状态.
With the fflush, some string
is sent to the file descriptor and then you truncate it. With no further flushing, the file stays truncated.
这篇关于对使用fopen打开的文件进行ftruncate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!