I'm using C to write some data to a file. I want to erase the previous text written in the file in case it was longer than what I'm writing now. I want to decrease the size of file or truncate until the end. How can I do this?



If you want to preserve the previous contents of the file up to some length (a length bigger than zero, which the other answers provide), then POSIX provides the truncate() and ftruncate() functions for the job.

#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);

The name indicates the primary purpose - shortening a file. But if the specified length is longer than the previous length, the file grows (zero padding) to the new size. Note that ftruncate() works on a file descriptor, not a FILE *; you could use:

if (ftruncate(fileno(fp), new_length) != 0) ...error handling...

It is likely, though, that for your purposes, truncate on open is all you need, and for that, the options given by others will be sufficient.


'Linux > C/C++' 카테고리의 다른 글

fcntl() 레코드 잠금  (0) 2012.07.11
ftruncate() 파일을 지정한 크기로 변경  (0) 2012.07.11
파일 유무 확인  (0) 2012.07.10
linux와 Windows의 파일 정보 접근  (0) 2012.07.10
linux GetTickCount  (0) 2012.07.10