基於c中使用ftruncate()前需要fflush(),使用後需要rewind()的深入探討

來源:互聯網
上載者:User

今天用 ftruncate截斷檔案, 但怎麼都不能達到預料的效果, 截斷後檔案中的內容比較雜, 而且檔案大小也保持原來的.
添加 fflush() 和 rewind() 後OK.
以下是測試代碼: 複製代碼 代碼如下:#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
FILE *fp;
char *file = "tmp";
int i;
int fd;

fp = fopen(file, "w");
if(fp == NULL)
{
printf("fopen failed\n");
return -1;
}

for(i=0; i<1000; i++)
{
fprintf(fp, "%d -- abcedfg \n", i);
}
fflush(fp);
fd = fileno(fp);
if(ftruncate(fd, 0)<0)
{
perror("");
return -1;
}
rewind(fp);
fprintf(fp, "end\n");
fclose(fp);
return 0;
}

程式運行後, tmp 檔案的內容為 end , 大小為4位元組.
- - - - - - - - - -
在調用 ftruncate() 前用 rewind() 也行.
但用 ftruncate()截斷過的檔案, 在用 fread, fwrite拷貝到另外一個檔案時, 會出現亂碼和一些'\0'字元. 改用 fgets 和 fputs 則正常.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.