/* ---------------------------------------------
** Test File Function
** author: smileonce 2005-06-16
*/
#include <stdio.h>
int freadline(FILE * f, char * buf);
int main(int argc, char* argv[])
{
FILE * f;
int i;
char buf[255];
// write some number to a file for testing.
f = fopen("F:\\tmp\\FileSy\\Debug\\testfile.txt", "w");
for (i=0; i<10; i++)
fprintf(f, "origin : %d\n", i);
fclose(f);
// test ...
f = fopen("F:\\tmp\\FileSy\\Debug\\testfile.txt", "r+");
for (i=0; i<5; i++)
{
freadline(f, buf);
printf("%s\n", buf);
}
fseek(f, 0L, SEEK_CUR); //use this to refresh the file,
//same function as fflush(), fgetpos(), fsetpos().
for (i=5; i<8; i++)
fprintf(f, "replace: %d\n", i);
fclose(f);
return 0;
}
// read a line from file stream
int freadline(FILE * f, char * buf)
{
int count=0, ch;
while((ch=fgetc(f)) != EOF)
if (ch != '\n')
buf[count++] = (char)ch;
else break;
buf[count++] = '\0';
return (ch == EOF ? ch : count);
}这是一个正确的程序了,你可以试一下去掉文中的那行看似没有任何意义的红字的代码有什么后果。答案是根本写不入数据。经过查证,支持程序打开一个文件,同时进行写入和读出操作的函数参数”r+”是很有历史的。早期的fopen函数并不支持它。为了保持和过去不能同时进行读写操作的程序的兼容性,一个输入操作不能随后直接紧跟着一个输出操作,反之亦然。如果要同时进行读写操作,必须在读写操作交换的地方插入fseek()、fgetpos()与fsetpos()、fflush()这三组的函数中的一个。fseek()最直接明了,一句话就可以搞定:
FILE *f; ... ... fseek( f, 0L, SEEK_CUR); ... ...
fgetpos()和fsetpos()写起来就比较麻烦,但也能起到作用,所以列在此处:
fpos_t pos; FILE *f; ... ... fgetpos( f, &pos ); //use these two lines fsetpos( f, &pos ); // replace fseek(f, 0L, SEEK_CUR); ... ...fflush()对于先读后写这种交替操作不起作用,所以推荐用上两个。
-------------

评论