How to cut the size of a text file? For example, at the end of the file there are 5 spaces, how to trim the end of the file into 5 bytes?
2 answers
#include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat s; stat(argv[1], &s); truncate(argv[1], s.st_size - 5); return 0; }
It's all right?
- alexlz, Please write an example for a specific file. And for some reason, my compiler does not understand "truncate". Compiler C-Free 4.0 - alexl1720p
- In Windows, gcc MinGW also does not understand. Open the file f = fopen (..., "r +") and do ftruncate (fileno (f), size) - avp
- Is the example for a particular file the contents of the "before" and "after"? Yes, any ... In the above text, the file name is specified by the first parameter of the command line argv [1]. Unix calls are used, so you may not have them. I have WinXP SP2, cygwin. How to do this with fopen / fseek / fwrite - difficult to answer. - alexlz
- And about mingw - there is limited support for posix and / or unix calls. - alexlz
- If you compile on Windows, then for Windows there is an analogue of the POSIX trancate - this is _chsize. - Nicolas Chabanovsky ♦
|
Windows version:
int f; if (_sopen_s(&f, "filename", _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE)) { _chsize(f, filesize); _close(f); }
- So this is essentially ftruncate (). truncate () takes the file name. - avp
- @ alexl1720p You should ask a new question, instead of creating a comment: there is too much code in it. - Nicolas Chabanovsky ♦
|