user-0 提问: C文件操作如何使文件指针找到文件末尾

回复:
user: user-1
content: fopen, _wfopen Open a file.  FILE *fopen( const char *filename, const char *mode );  FILE *_wfopen( const wchar_t *filename, const wchar_t *mode );  Function Required Header Compatibility  fopen <stdio.h> ANSI, Win 95, Win NT  _wfopen <stdio.h> or <wchar.h> 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    The c, n, and t mode options are Microsoft extensions for fopen and _fdopen and should not be used where ANSI portability is desired.  Return Value  Each of these functions returns a pointer to the open file. A null pointer value indicates an error.   Parameters  filename  Filename  mode  Type of access permitted  Remarks  The fopen function opens the file specified by filename. _wfopen is a wide-character version of fopen; the arguments to _wfopen are wide-character strings. _wfopen and fopen behave identically otherwise.  Generic-Text Routine Mappings  TCHAR.H Routine  _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined  _tfopen fopen fopen _wfopen    The character string mode specifies the type of access requested for the file, as follows:  "r"  Opens for reading. If the file does not exist or cannot be found, the fopen call fails.  "w"  Opens an empty file for writing. If the given file exists, its contents are destroyed.  "a"  Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn’t exist.  "r+"  Opens for both reading and writing. (The file must exist.)  "w+"  Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.  "a+"  Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn’t exist.  When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.  The "a" mode does not remove the EOF marker before appending to the file. After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data appended to the file. The "a+" mode does remove the EOF marker before appending to the file. After appending, the MS-DOS TYPE command shows all data in the file. The "a+" mode is required for appending to a stream file that is terminated with the CTRL+Z EOF marker.  When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for “update”). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.  In addition to the above values, the following characters can be included in mode to specify the translation mode for newline characters:  t  Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing with "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with a CTRL+Z, may cause fseek to behave improperly near the end of the file.   Also, in text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).  b  Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.   If t or b is not given in mode, the default translation mode is defined by the global variable _fmode. If t or b is prefixed to the argument, the function fails and returns NULL.   For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.  c  Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called.  n  Reset the commit flag for the associated filename to “no-commit.” This is the default. It also overrides the global commit flag if you link your program with COMMODE.OBJ. The global commit flag default is “no-commit” unless you explicitly link your program with COMMODE.OBJ.  Valid characters for the mode string used in fopen and _fdopen correspond to oflag arguments used in _open and _sopen, as follows.  Characters in mode String Equivalent oflag Value for _open/_sopen   a _O_WRONLY | _O_APPEND (usually _O_WRONLY | _O_CREAT | _O_APPEND)  a+ _O_RDWR | _O_APPEND (usually _O_RDWR | _O_APPEND | _O_CREAT )  r _O_RDONLY  r+ _O_RDWR  w _O_WRONLY (usually _O_WRONLY | _O_CREAT | _O_TRUNC)  w+ _O_RDWR (usually _O_RDWR | _O_CREAT | _O_TRUNC)  b _O_BINARY  t _O_TEXT  c None  n None    Example  /* FOPEN.C: This program opens files named "data"  * and "data2".It  uses fclose to close "data" and  * _fcloseall to close all remaining files.  */  #include <stdio.h>  FILE *stream, *stream2;  void main( void ) {    int numclosed;     /* Open for read (will fail if file "data" does not exist) */    if( (stream  = fopen( "data", "r" )) == NULL )       printf( "The file 'data' was not opened\n" );    else       printf( "The file 'data' was opened\n" );     /* Open for write */    if( (stream2 = fopen( "data2", "w+" )) == NULL )       printf( "The file 'data2' was not opened\n" );    else       printf( "The file 'data2' was opened\n" );     /* Close stream */    if( fclose( stream ) )       printf( "The file 'data' was not closed\n" );     /* All other files are closed: */    numclosed = _fcloseall( );    printf( "Number of files closed by _fcloseall: %u\n", numclosed ); }   Output  The file 'data' was opened The file 'data2' was opened Number of files closed by _fcloseall: 1   Stream I/O Routines  See Also   fclose, _fdopen, ferror, _fileno, freopen, _open, _setmode

user: user-2
content: fseek(fp,0,2);

user: user-3
content: 引用 3 楼 Saiko_YAMP 的回复:[quote=引用 2 楼 zilaishuichina 的回复:] 直接移动到末尾用 fseek 判断是否移动到末尾用 feof 	int n=1; 	INT_PTR nRes;    	nRes = MessageBox(_T("您确定要进行添加吗？"), _T(""), MB_OKCANCEL | MB_ICONQUESTION); 	Cdata cdata(eat,transport,life,Else,month,day); 	FILE *fp; 	if(n==1){ 		if((fp=fopen("data.txt","wb"))==NULL){ 			exit(0); 		} 		for(;feof(fp);) 		{ 			fseek(fp,1L,1); 		} 		 			fprintf(fp,"%f %f %f %f %f %f\n", 			cdata.eat, 			cdata.transport, 			cdata.life, 			cdata.Else, 			cdata.month, 			cdata.day); 		INT_PTR nRess; 		nRess=MessageBox(_T("文件写入成功！"), _T(""), MB_OK); 		 		fclose(fp); 	} 我的这段代码是怎么了？为什么每次写入文件都会把之前的代码删掉重写[/quote]  fopen的mode有下列几种形态字符串: r 以只读方式打开文件，该文件必须存在。 r+ 以可读写方式打开文件，该文件必须存在。 rb+ 读写打开一个二进制文件，允许读写数据，文件必须存在。 w 打开只写文件，若文件存在则文件长度清为0，即该文件内容会消失。若文件不存在则建立该文件。 w+ 打开可读写文件，若文件存在则文件长度清为零，即该文件内容会消失。若文件不存在则建立该文件。 a 以附加的方式打开只写文件。若文件不存在，则会建立该文件，如果文件存在，写入的数据会被加到文件尾，即文件原先的内容会被保留。（EOF符保留） a+ 以附加方式打开可读写的文件。若文件不存在，则会建立该文件，如果文件存在，写入的数据会被加到文件尾后，即文件原先的内容会被保留。 （原来的EOF符不保留） wb 只写打开或新建一个二进制文件；只允许写数据。 wb+ 读写打开或建立一个二进制文件，允许读和写。 ab+ 读写打开一个二进制文件，允许读或在文件末追加数据。 wx 创建文本文件,只允许写入数据.[C11] wbx 创建一个二进制文件,只允许写入数据.[C11] w+x 创建一个文本文件,允许读写.[C11] wb+x 创建一个二进制文件,允许读写.[C11] w+bx 和"wb+x"相同[C11]

user: user-4
content: 楼上正解， 打开方式不正确

user: user-5
content: fopen("data.txt","wb") LZ还知道wb表示什么？

user: user-6
content: fopen("data.txt","wb")   // "wb"参数表示二进制写打开,并且如果文件在, 会被清除.

user: user-7
content: 最好看下 MSDN 上 fopen 和 fseek 的说明：  fopen 函数的说明 fseek 函数的说明

user: user-7
content: 引用 3 楼 Saiko_YAMP 的回复:[quote=引用 2 楼 zilaishuichina 的回复:] 直接移动到末尾用 fseek 判断是否移动到末尾用 feof 	int n=1; 	INT_PTR nRes;    	nRes = MessageBox(_T("您确定要进行添加吗？"), _T(""), MB_OKCANCEL | MB_ICONQUESTION); 	Cdata cdata(eat,transport,life,Else,month,day); 	FILE *fp; 	if(n==1){ 		if((fp=fopen("data.txt","wb"))==NULL){ 			exit(0); 		} 		for(;feof(fp);) 		{ 			fseek(fp,1L,1); 		} 		 			fprintf(fp,"%f %f %f %f %f %f\n", 			cdata.eat, 			cdata.transport, 			cdata.life, 			cdata.Else, 			cdata.month, 			cdata.day); 		INT_PTR nRess; 		nRess=MessageBox(_T("文件写入成功！"), _T(""), MB_OK); 		 		fclose(fp); 	} 我的这段代码是怎么了？为什么每次写入文件都会把之前的代码删掉重写[/quote]  for(;feof(fp);) { 	fseek(fp,1L,1); } 这段是啥意思？  从文件末尾写入的话，直接用 fseek(fp, SEEK_END, 0); 没有 SEEK_END 常数的话就 fseek(fp, 2, 0);  另外如果你是每次都从文件末尾写入的话，打开文件的时候直接指定追加写入就可以： fp=fopen("data.txt","a+b"))

user: user-0
content: 引用 3 楼 Saiko_YAMP 的回复:[quote=引用 2 楼 zilaishuichina 的回复:] 直接移动到末尾用 fseek 判断是否移动到末尾用 feof 	int n=1; 	INT_PTR nRes;    	nRes = MessageBox(_T("您确定要进行添加吗？"), _T(""), MB_OKCANCEL | MB_ICONQUESTION); 	Cdata cdata(eat,transport,life,Else,month,day); 	FILE *fp; 	if(n==1){ 		if((fp=fopen("data.txt","wb"))==NULL){ 			exit(0); 		} 		for(;feof(fp);) 		{ 			fseek(fp,1L,1); 		} 		 			fprintf(fp,"%f %f %f %f %f %f\n", 			cdata.eat, 			cdata.transport, 			cdata.life, 			cdata.Else, 			cdata.month, 			cdata.day); 		INT_PTR nRess; 		nRess=MessageBox(_T("文件写入成功！"), _T(""), MB_OK); 		 		fclose(fp); 	} 我的这段代码是怎么了？为什么每次写入文件都会把之前的数据删掉重写[/quote].

user: user-0
content: 引用 2 楼 zilaishuichina 的回复:直接移动到末尾用 fseek 判断是否移动到末尾用 feof 	int n=1; 	INT_PTR nRes;    	nRes = MessageBox(_T("您确定要进行添加吗？"), _T(""), MB_OKCANCEL | MB_ICONQUESTION); 	Cdata cdata(eat,transport,life,Else,month,day); 	FILE *fp; 	if(n==1){ 		if((fp=fopen("data.txt","wb"))==NULL){ 			exit(0); 		} 		for(;feof(fp);) 		{ 			fseek(fp,1L,1); 		} 		 			fprintf(fp,"%f %f %f %f %f %f\n", 			cdata.eat, 			cdata.transport, 			cdata.life, 			cdata.Else, 			cdata.month, 			cdata.day); 		INT_PTR nRess; 		nRess=MessageBox(_T("文件写入成功！"), _T(""), MB_OK); 		 		fclose(fp); 	} 我的这段代码是怎么了？为什么每次写入文件都会把之前的代码删掉重写

user: user-3
content: 直接移动到末尾用 fseek 判断是否移动到末尾用 feof

user: user-8
content: fseek()