user-0 提问: fseek回退覆写文件，如何结尾？EOF无效呢

回复:
user: user-0
content: 引用 16 楼 zhao4zhong1 的回复:_chsize Changes the file size.  int _chsize( int handle, long size );  Routine Required Header Optional Headers Compatibility  _chsize <io.h> <errno.h> Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  _chsize returns the value 0 if the file size is successfully changed. A return value of –1 indicates an error: errno is set to EACCES if the specified file is locked against access, to EBADF if the specified file is read-only or the handle is invalid, or to ENOSPC if no space is left on the device.  Parameters  handle  Handle referring to open file  size  New length of file in bytes  Remarks  The _chsize function extends or truncates the file associated with handle to the length specified by size. The file must be open in a mode that permits writing. Null characters ('\0') are appended if the file is extended. If the file is truncated, all data from the end of the shortened file to the original length of the file is lost.  Example   /* CHSIZE.C: This program uses _filelength to report the size  * of a file before and after modifying it with _chsize.  */  #include <io.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h>  void main( void ) {    int fh, result;    unsigned int nbytes = BUFSIZ;     /* Open a file */    if( (fh = _open( "data", _O_RDWR | _O_CREAT, _S_IREAD                     | _S_IWRITE ))  != -1 )    {       printf( "File length before: %ld\n", _filelength( fh ) );       if( ( result = _chsize( fh, 329678 ) ) == 0 )          printf( "Size successfully changed\n" );       else          printf( "Problem in changing the size\n" );       printf( "File length after:  %ld\n", _filelength( fh ) );       _close( fh );    } }   Output  File length before: 0 Size successfully changed File length after:  329678     File Handling Routines  See Also   _close, _creat, _open 您好，我在C标准库中，没有找到io.h呢，这几个方法也就没发现。。。

user: user-0
content: 引用 14 楼 codedoctor 的回复:[quote=引用 6 楼 sys0613 的回复:] [quote=引用 4 楼 codedoctor 的回复:] 我的意思就是直接全部重写。先直接seek到结尾，再全部装入string中进行处理，处理完之后再重新写入 当文件过大时，你这招就不太好用了[/quote]  ..你这不是抬杠吗，如果你要说大文件的话，那么你这个怎么定位输入的位置就不说了（还是得读取文件内容），而且频繁的对存储器进行读入读出是非常不好的习惯，比较好的方法就是一次读取尽可能大的数据然后进行处理再一次性的取出，而不是直接就在文件的映射区里面进行操作。 我只是针对你这个问题提出的最方便的解决方案，你要说去操作一个几个G的txt文件。那当我没有回答吧[/quote] 抱歉，还是谢谢您了

user: user-1
content: TRUNCATE Section: Linux Programmer's Manual (2) Updated: 2004-06-23  --------------------------------------------------------------------------------    NAME truncate, ftruncate - truncate a file to a specified length    SYNOPSIS #include <unistd.h>  #include <sys/types.h>  int truncate(const char *path, off_t length);  int ftruncate(int fd, off_t length);     DESCRIPTION The truncate and ftruncate functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.  If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as zero bytes.   The file pointer is not changed.   If the size changed, then the ctime and mtime fields for the file are updated, and suid and sgid mode bits may be cleared.   With ftruncate, the file must be open for writing; with truncate, the file must be writable.     RETURN VALUE On success, zero is returned. On error, -1 is returned, and errno is set appropriately.    ERRORS For truncate:  EACCES  Search permission is denied for a component of the path prefix, or the named file is not writable by the user. (See also path_resolution(2).)  EFAULT  Path points outside the process's allocated address space.  EFBIG  The argument length is larger than the maximum file size. (XSI)  EINTR  A signal was caught during execution.  EINVAL  The argument length is negative or larger than the maximum file size.  EIO  An I/O error occurred updating the inode.  EISDIR  The named file is a directory.  ELOOP  Too many symbolic links were encountered in translating the pathname.  ENAMETOOLONG  A component of a pathname exceeded 255 characters, or an entire path name exceeded 1023 characters.  ENOENT  The named file does not exist.  ENOTDIR  A component of the path prefix is not a directory.  EROFS  The named file resides on a read-only file system.  ETXTBSY  The file is a pure procedure (shared text) file that is being executed.  For ftruncate the same errors apply, but instead of things that can be wrong with path, we now have things that can be wrong with fd:   EBADF  The fd is not a valid descriptor.  EBADF or EINVAL  The fd is not open for writing.  EINVAL  The fd does not reference a regular file.     CONFORMING TO 4.4BSD, SVr4 (these function calls first appeared in BSD 4.2). POSIX 1003.1-1996 has ftruncate. POSIX 1003.1-2001 also has truncate, as an XSI extension.  SVr4 documents additional truncate error conditions EMFILE, EMULTIHP, ENFILE, ENOLINK. SVr4 documents for ftruncate an additional EAGAIN error condition.     NOTES The above description is for XSI-compliant systems. For non-XSI-compliant systems, the POSIX standard allows two behaviours for ftruncate when length exceeds the file length (note that truncate is not specified at all in such an environment): either returning an error, or extending the file. (Most Unices follow the XSI requirement.)    SEE ALSO open(2), path_resolution(2)  --------------------------------------------------------------------------------

user: user-2
content: 还需要自己截断文件，参看：http://blog.csdn.net/qq_32541007/article/details/51193886

user: user-3
content: 我的意思就是直接全部重写。先直接seek到结尾，再全部装入string中进行处理，处理完之后再重新写入

user: user-4
content: 接楼上 https://msdn.microsoft.com/en-us/library/aa246710(v=vs.60).aspx #include <stdio.h> //#include <stdlib.h> //#include <string.h> #include <io.h> #include <fcntl.h> //#include <sys/types.h> #include <sys/stat.h>   int main(void) {    long len;    int fh, result;    FILE *fp1 = fopen("3.txt", "w");    fputs("1234567654321", fp1);    fseek(fp1, -5, SEEK_CUR);    fputs("88", fp1);    len = ftell(fp1);    fclose(fp1);     /* Open a file */    if ((fh = _open("3.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)    {       printf("File length before: %ld\n", _filelength(fh));       if ((result = _chsize(fh, len)) == 0)          printf("Size successfully changed\n");       else          printf("Problem in changing the size\n");       printf("File length after:  %ld\n", _filelength(fh));       _close(fh);    }        return 0; }

user: user-0
content: 引用 1 楼 Loydia 的回复:这种情况一般会重写文件吧。另外有个函数你可以研究下：chsize 我理解这种情况应该不会重写文件，只是替换了倒数第四位和第五位，同时指针停留在倒数第三位。我就是想在倒数第三位处写入一个停止。。。不知道应该如何实现

user: user-5
content: 这种情况一般会重写文件吧。另外有个函数你可以研究下：chsize

user: user-1
content: _chsize Changes the file size.  int _chsize( int handle, long size );  Routine Required Header Optional Headers Compatibility  _chsize <io.h> <errno.h> Win 95, Win NT    For additional compatibility information, see Compatibility in the Introduction.  Libraries  LIBC.LIB Single thread static library, retail version  LIBCMT.LIB Multithread static library, retail version  MSVCRT.LIB Import library for MSVCRT.DLL, retail version    Return Value  _chsize returns the value 0 if the file size is successfully changed. A return value of –1 indicates an error: errno is set to EACCES if the specified file is locked against access, to EBADF if the specified file is read-only or the handle is invalid, or to ENOSPC if no space is left on the device.  Parameters  handle  Handle referring to open file  size  New length of file in bytes  Remarks  The _chsize function extends or truncates the file associated with handle to the length specified by size. The file must be open in a mode that permits writing. Null characters ('\0') are appended if the file is extended. If the file is truncated, all data from the end of the shortened file to the original length of the file is lost.  Example   /* CHSIZE.C: This program uses _filelength to report the size  * of a file before and after modifying it with _chsize.  */  #include <io.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h>  void main( void ) {    int fh, result;    unsigned int nbytes = BUFSIZ;     /* Open a file */    if( (fh = _open( "data", _O_RDWR | _O_CREAT, _S_IREAD                     | _S_IWRITE ))  != -1 )    {       printf( "File length before: %ld\n", _filelength( fh ) );       if( ( result = _chsize( fh, 329678 ) ) == 0 )          printf( "Size successfully changed\n" );       else          printf( "Problem in changing the size\n" );       printf( "File length after:  %ld\n", _filelength( fh ) );       _close( fh );    } }   Output  File length before: 0 Size successfully changed File length after:  329678     File Handling Routines  See Also   _close, _creat, _open

user: user-3
content: 当然也是我自己没看清你的题

user: user-3
content: 引用 6 楼 sys0613 的回复:[quote=引用 4 楼 codedoctor 的回复:] 我的意思就是直接全部重写。先直接seek到结尾，再全部装入string中进行处理，处理完之后再重新写入 当文件过大时，你这招就不太好用了[/quote]  ..你这不是抬杠吗，如果你要说大文件的话，那么你这个怎么定位输入的位置就不说了（还是得读取文件内容），而且频繁的对存储器进行读入读出是非常不好的习惯，比较好的方法就是一次读取尽可能大的数据然后进行处理再一次性的取出，而不是直接就在文件的映射区里面进行操作。 我只是针对你这个问题提出的最方便的解决方案，你要说去操作一个几个G的txt文件。那当我没有回答吧

user: user-4
content: 我的也是纯C

user: user-0
content: 引用 11 楼 Intel0011 的回复:我的是VC6.0的   [/code]  那应该不行吧，你是c++吧？我是纯c，得考虑兼容性什么的，应该不能用vc6.0

user: user-4
content: 我的是VC6.0的 /*** *io.h - declarations for low-level file handling and I/O functions * *       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved. * *Purpose: *       This file contains the function declarations for the low-level *       file handling and I/O functions. * *       [Public] * ****/  #if     _MSC_VER > 1000 #pragma once #endif  #ifndef _INC_IO #define _INC_IO  #if     !defined(_WIN32) && !defined(_MAC) #error ERROR: Only Mac or Win32 targets supported! #endif   #ifdef  _MSC_VER /*  * Currently, all MS C compilers for Win32 platforms default to 8 byte  * alignment.  */ #pragma pack(push,8) #endif  /* _MSC_VER */  #ifndef _POSIX_  #ifdef  __cplusplus extern "C" { #endif    /* Define _CRTIMP */  #ifndef _CRTIMP #ifdef  _DLL #define _CRTIMP __declspec(dllimport) #else   /* ndef _DLL */ #define _CRTIMP #endif  /* _DLL */ #endif  /* _CRTIMP */   /* Define __cdecl for non-Microsoft compilers */  #if     ( !defined(_MSC_VER) && !defined(__cdecl) ) #define __cdecl #endif  /* Define _CRTAPI1 (for compatibility with the NT SDK) */  #ifndef _CRTAPI1 #if	_MSC_VER >= 800 && _M_IX86 >= 300 #define _CRTAPI1 __cdecl #else #define _CRTAPI1 #endif #endif  #ifndef _MAC #ifndef _WCHAR_T_DEFINED typedef unsigned short wchar_t; #define _WCHAR_T_DEFINED #endif #endif  /* ndef _MAC */  #ifndef _TIME_T_DEFINED typedef long time_t;            /* time value */ #define _TIME_T_DEFINED         /* avoid multiple def's of time_t */ #endif  #ifndef _FSIZE_T_DEFINED typedef unsigned long _fsize_t; /* Could be 64 bits for Win32 */ #define _FSIZE_T_DEFINED #endif  #ifndef _MAC  #ifndef _FINDDATA_T_DEFINED  struct _finddata_t {     unsigned    attrib;     time_t      time_create;    /* -1 for FAT file systems */     time_t      time_access;    /* -1 for FAT file systems */     time_t      time_write;     _fsize_t    size;     char        name[260]; };  #if     _INTEGRAL_MAX_BITS >= 64 struct _finddatai64_t {     unsigned    attrib;     time_t      time_create;    /* -1 for FAT file systems */     time_t      time_access;    /* -1 for FAT file systems */     time_t      time_write;     __int64     size;     char        name[260]; }; #endif  #define _FINDDATA_T_DEFINED #endif  #ifndef _WFINDDATA_T_DEFINED  struct _wfinddata_t {     unsigned    attrib;     time_t      time_create;    /* -1 for FAT file systems */     time_t      time_access;    /* -1 for FAT file systems */     time_t      time_write;     _fsize_t    size;     wchar_t     name[260]; };  #if     _INTEGRAL_MAX_BITS >= 64 struct _wfinddatai64_t {     unsigned    attrib;     time_t      time_create;    /* -1 for FAT file systems */     time_t      time_access;    /* -1 for FAT file systems */     time_t      time_write;     __int64     size;     wchar_t     name[260]; }; #endif  #define _WFINDDATA_T_DEFINED #endif  /* File attribute constants for _findfirst() */  #define _A_NORMAL       0x00    /* Normal file - No read/write restrictions */ #define _A_RDONLY       0x01    /* Read only file */ #define _A_HIDDEN       0x02    /* Hidden file */ #define _A_SYSTEM       0x04    /* System file */ #define _A_SUBDIR       0x10    /* Subdirectory */ #define _A_ARCH         0x20    /* Archive file */  #endif  /* ndef _MAC */  /* function prototypes */  _CRTIMP int __cdecl _access(const char *, int); _CRTIMP int __cdecl _chmod(const char *, int); _CRTIMP int __cdecl _chsize(int, long); _CRTIMP int __cdecl _close(int); _CRTIMP int __cdecl _commit(int); _CRTIMP int __cdecl _creat(const char *, int); _CRTIMP int __cdecl _dup(int); _CRTIMP int __cdecl _dup2(int, int); _CRTIMP int __cdecl _eof(int); _CRTIMP long __cdecl _filelength(int); #ifndef _MAC _CRTIMP long __cdecl _findfirst(const char *, struct _finddata_t *); _CRTIMP int __cdecl _findnext(long, struct _finddata_t *); _CRTIMP int __cdecl _findclose(long); #endif  /* ndef _MAC */ _CRTIMP int __cdecl _isatty(int); _CRTIMP int __cdecl _locking(int, int, long); _CRTIMP long __cdecl _lseek(int, long, int); _CRTIMP char * __cdecl _mktemp(char *); _CRTIMP int __cdecl _open(const char *, int, ...); #ifndef _MAC _CRTIMP int __cdecl _pipe(int *, unsigned int, int); #endif  /* ndef _MAC */ _CRTIMP int __cdecl _read(int, void *, unsigned int); _CRTIMP int __cdecl remove(const char *); _CRTIMP int __cdecl rename(const char *, const char *); _CRTIMP int __cdecl _setmode(int, int); _CRTIMP int __cdecl _sopen(const char *, int, int, ...); _CRTIMP long __cdecl _tell(int); _CRTIMP int __cdecl _umask(int); _CRTIMP int __cdecl _unlink(const char *); _CRTIMP int __cdecl _write(int, const void *, unsigned int);  #if     _INTEGRAL_MAX_BITS >= 64 _CRTIMP __int64 __cdecl _filelengthi64(int); _CRTIMP long __cdecl _findfirsti64(const char *, struct _finddatai64_t *); _CRTIMP int __cdecl _findnexti64(long, struct _finddatai64_t *); _CRTIMP __int64 __cdecl _lseeki64(int, __int64, int); _CRTIMP __int64 __cdecl _telli64(int); #endif  #ifndef _MAC #ifndef _WIO_DEFINED  /* wide function prototypes, also declared in wchar.h  */  _CRTIMP int __cdecl _waccess(const wchar_t *, int); _CRTIMP int __cdecl _wchmod(const wchar_t *, int); _CRTIMP int __cdecl _wcreat(const wchar_t *, int); _CRTIMP long __cdecl _wfindfirst(const wchar_t *, struct _wfinddata_t *); _CRTIMP int __cdecl _wfindnext(long, struct _wfinddata_t *); _CRTIMP int __cdecl _wunlink(const wchar_t *); _CRTIMP int __cdecl _wrename(const wchar_t *, const wchar_t *); _CRTIMP int __cdecl _wopen(const wchar_t *, int, ...); _CRTIMP int __cdecl _wsopen(const wchar_t *, int, int, ...); _CRTIMP wchar_t * __cdecl _wmktemp(wchar_t *);  #if     _INTEGRAL_MAX_BITS >= 64 _CRTIMP long __cdecl _wfindfirsti64(const wchar_t *, struct _wfinddatai64_t *); _CRTIMP int __cdecl _wfindnexti64(long, struct _wfinddatai64_t *); #endif  #define _WIO_DEFINED #endif #endif  /* ndef _MAC */   _CRTIMP long __cdecl _get_osfhandle(int); _CRTIMP int __cdecl _open_osfhandle(long, int);  #if     !__STDC__  /* Non-ANSI names for compatibility */  _CRTIMP int __cdecl access(const char *, int); _CRTIMP int __cdecl chmod(const char *, int); _CRTIMP int __cdecl chsize(int, long); _CRTIMP int __cdecl close(int); _CRTIMP int __cdecl creat(const char *, int); _CRTIMP int __cdecl dup(int); _CRTIMP int __cdecl dup2(int, int); _CRTIMP int __cdecl eof(int); _CRTIMP long __cdecl filelength(int); _CRTIMP int __cdecl isatty(int); _CRTIMP int __cdecl locking(int, int, long); _CRTIMP long __cdecl lseek(int, long, int); _CRTIMP char * __cdecl mktemp(char *); _CRTIMP int __cdecl open(const char *, int, ...); _CRTIMP int __cdecl read(int, void *, unsigned int); _CRTIMP int __cdecl setmode(int, int); _CRTIMP int __cdecl sopen(const char *, int, int, ...); _CRTIMP long __cdecl tell(int); _CRTIMP int __cdecl umask(int); _CRTIMP int __cdecl unlink(const char *); _CRTIMP int __cdecl write(int, const void *, unsigned int);  #endif  /* __STDC__ */  #ifdef  __cplusplus } #endif  #endif  /* _POSIX_ */  #ifdef  _MSC_VER #pragma pack(pop) #endif  /* _MSC_VER */  #endif  /* _INC_IO */

user: user-0
content: 引用 3 楼 Intel0011 的回复:接楼上 https://msdn.microsoft.com/en-us/library/aa246710(v=vs.60).aspx #include <stdio.h> //#include <stdlib.h> //#include <string.h> #include <io.h> #include <fcntl.h> //#include <sys/types.h> #include <sys/stat.h>   int main(void) {    long len;    int fh, result;    FILE *fp1 = fopen("3.txt", "w");    fputs("1234567654321", fp1);    fseek(fp1, -5, SEEK_CUR);    fputs("88", fp1);    len = ftell(fp1);    fclose(fp1);     /* Open a file */    if ((fh = _open("3.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)    {       printf("File length before: %ld\n", _filelength(fh));       if ((result = _chsize(fh, len)) == 0)          printf("Size successfully changed\n");       else          printf("Problem in changing the size\n");       printf("File length after:  %ld\n", _filelength(fh));       _close(fh);    }        return 0; }  没有io.h呢？

user: user-0
content: 引用 3 楼 Intel0011 的回复:接楼上 https://msdn.microsoft.com/en-us/library/aa246710(v=vs.60).aspx #include <stdio.h> //#include <stdlib.h> //#include <string.h> #include <io.h> #include <fcntl.h> //#include <sys/types.h> #include <sys/stat.h>   int main(void) {    long len;    int fh, result;    FILE *fp1 = fopen("3.txt", "w");    fputs("1234567654321", fp1);    fseek(fp1, -5, SEEK_CUR);    fputs("88", fp1);    len = ftell(fp1);    fclose(fp1);     /* Open a file */    if ((fh = _open("3.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)    {       printf("File length before: %ld\n", _filelength(fh));       if ((result = _chsize(fh, len)) == 0)          printf("Size successfully changed\n");       else          printf("Problem in changing the size\n");       printf("File length after:  %ld\n", _filelength(fh));       _close(fh);    }        return 0; }   请问_open是什么函数？使用的是标准库？谢谢

user: user-0
content: 引用 3 楼 Intel0011 的回复:接楼上 https://msdn.microsoft.com/en-us/library/aa246710(v=vs.60).aspx #include <stdio.h> //#include <stdlib.h> //#include <string.h> #include <io.h> #include <fcntl.h> //#include <sys/types.h> #include <sys/stat.h>   int main(void) {    long len;    int fh, result;    FILE *fp1 = fopen("3.txt", "w");    fputs("1234567654321", fp1);    fseek(fp1, -5, SEEK_CUR);    fputs("88", fp1);    len = ftell(fp1);    fclose(fp1);     /* Open a file */    if ((fh = _open("3.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)    {       printf("File length before: %ld\n", _filelength(fh));       if ((result = _chsize(fh, len)) == 0)          printf("Size successfully changed\n");       else          printf("Problem in changing the size\n");       printf("File length after:  %ld\n", _filelength(fh));       _close(fh);    }        return 0; }   好的，谢谢，我试试看，这个与编译器什么的绑定么？我想要一个通用的，不要受什么版本限制什么的

user: user-6
content: fseek只能控制文件描述的位置，它不会对文件内容做任何修改； 对于楼主的需求，可以通过两种方法实现： 一种覆盖法，文件已经存在的数据，是fseek定位到文件的位置，然后输入"88"，然后后面的数据用空格覆盖； 另一种办法，就是将文件的内容读到内存，在内存里直接操作，然后重新刷到文件里。 至于使用那种办法，要根据实际需求；

user: user-0
content: 引用 4 楼 codedoctor 的回复:我的意思就是直接全部重写。先直接seek到结尾，再全部装入string中进行处理，处理完之后再重新写入 当文件过大时，你这招就不太好用了