[英]Why is the data write not reflected to the file using fprintf file stream
這是我的程序:
#include <stdio.h>
int main() {
FILE *logh;
logh = fopen("/home/user1/data.txt", "a+");
if (logh == NULL)
{
printf("error creating file \n");
return -1;
}
// write some data to the log handle and check if it gets written..
int result = fprintf(logh, "this is some test data \n");
if (result > 0)
printf("write successful \n");
else
printf("couldn't write the data to filesystem \n");
while (1) {
};
fclose(logh);
return 0;
}
當我運行該程序時,我看到正在創建文件,但它不包含任何數據。 我的理解是,在將數據實際寫入文件系統之前,內存中已經有數據緩存,以避免多個IO提高性能。 而且我也知道我可以在程序內部調用fsync / fdatasync來強制同步。 但是我可以在不更改程序的情況下從外部強制進行同步嗎?
我嘗試從Linux shell運行sync
命令,但是它不會使數據顯示在文件中。 :(
如果有人知道其他替代方法,請提供幫助。
一個有用的信息:我對此進行了進一步研究,最終發現,要完全刪除內部緩沖,可以使用int setvbuf(FILE *stream, char *buf, int mode, size_t size)
將FILE
模式設置為_IONBF
問題是由於您的while
語句,您的程序無法關閉文件。 刪除這些行:
while (1) {
};
如果打算永遠等待,則在執行while
語句之前,先用fclose
關閉文件。
IO函數使用FILE
指針將要寫入的數據緩存在程序內存中的內部緩沖區中,直到他們決定執行系統調用以“真正”寫入它為止(這通常用於普通文件,通常是在緩存的數據大小達到BUFSIZ
)。 在此之前,還沒有辦法從程序外部強制進行書寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.