如何在写文件的时候,将文件的长度截短
原来有一个文件,比如长度是2048字节,现在打开此文件,移动指针到100的位置,再写入200字节,此时不再需要后边的文件内容,即把文件长度截短为300字节,该如何处理?
char str[1024]="12345678890";
FILE* fp;
fp=fopen("test.dat","w+b");
fseek(fp,100,SEEK_SET);
fwrite(str,1,200,fp);
// 此处如何截短文件的长度为100+200=300字节呢?
fclose(fp);
问题点数:20、回复次数:5Top
1 楼cnwolf(独狼)回复于 2006-03-01 19:09:56 得分 3
文件是流,没有好办法
把文件内容读出来,重新创建Top
2 楼Mackz(在相互)回复于 2006-03-01 19:47:53 得分 6
SetEndOfFile
The SetEndOfFile function moves the end-of-file (EOF) position for the specified file to the current position of the file pointer.
Remarks
This function can be used to truncate or extend a file. If the file is extended, the contents of the file between the old EOF position and the new position are not defined.
Top
3 楼vcmute(BCare4 H1Rest Good9!)回复于 2006-03-01 22:48:27 得分 5
_chsize(fileno(fp),300);Top
4 楼DentistryDoctor(不在无聊中无奈,就在沉默中变态)回复于 2006-03-01 22:49:59 得分 5
API:SetEndOfFile
Or CFile::SetLengthTop
5 楼BombZhang(我当大哥很久了)回复于 2006-03-01 22:58:56 得分 1
你从100的位置写了以后原文件中100以后的值就已经被砍掉了,此时文件的长度就是300Top




