windows下似乎可以調(diào)用API SetFileSize
但是不甚確定,樓主自己查查MSDN吧 呵呵
可以通過(guò)系統(tǒng)提供的API來(lái)設(shè)置文件結(jié)尾,
在Linux下可以包含fcntl.h,使用int chsize(int handle, long size);
在windows下有SetFilePointer SetEndOfFile,請(qǐng)參閱MSDN
這些都是文件稍微底層的操作,所以標(biāo)準(zhǔn)C庫(kù)函數(shù)里面沒(méi)有
#include <io.h>
int main(void)
{
int handle;
char buf[11] = "0123456789 ";
/* create text file containing 10 bytes */
handle = open( "DUMMY.FIL ", O_CREAT);
write(handle, buf, strlen(buf));
/* truncate the file to 5 bytes in size */
chsize(handle, 5);
/* close the file */
close(handle);
return 0;
}
下面
ftruncate 好象是linux上的吧,windows上沒(méi)有
long pos;
FILE *file;
file=fopen( "filename ", "w+ ");
pos=ftell(file); //獲取當(dāng)前文件指針位置
ftruncate(fileno(file),pos); //根據(jù)大小截取文件。
#include "stdafx.h "
#include "iostream "
#include "stdio.h "
#include "stdlib.h "
#include "windows.h "
#include "io.h "
using namespace std;
int main()
{
FILE* f = fopen( "a.txt ", "r+ ");
char sz[128];
fgets(sz, 128, f);
HANDLE h = (HANDLE)_get_osfhandle(_fileno(f));
SetFilePointer(h, ftell(f), NULL, FILE_BEGIN);
SetEndOfFile(h);
fclose(f);
return 0;
}