- 论坛徽章:
- 0
|
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main( void )
{
FILE *stream;
char ch = '1';
char buf[60] = "123";
int n = 0;
stream = fopen( "./Debug/fseek.txt", "w+" );
if( stream == NULL )
{
printf( "The file fseek.out was not opened\n" );
return;
}
if(strlen(buf) != fwrite(buf, 1, strlen(buf), stream))
{
printf( "Error!\n" );
goto MAIN_GT1;
}
rewind(stream);
printf( "Position 1: %ld\n", ftell( stream) );//[]
if(0 != fseek(stream, 1, SEEK_CUR))
{
printf( "Error! fseek != 0 \n" );
goto MAIN_GT1;
}
printf( "Position 2: %ld\n", ftell( stream) );//[]
while(1 == fread(&ch, 1, 1, stream))
{
printf( "Position 3: %ld, ch = %c\n", ftell( stream), ch );//[]
if(0 != fseek(stream, -1, SEEK_CUR))
{
printf( "Error! fseek != 0 \n" );
goto MAIN_GT1;
}
printf( "Position 4: %ld\n", ftell( stream ) );//[]
ch++;
if(1 != fwrite(&ch, 1, 1, stream))
{
printf( "Error! fwrite != 0 \n" );
goto MAIN_GT1;
}
printf( "Position 5: %ld\n", ftell( stream ) );//[]
//_getch();
// goto MAIN_GT1;
//n++;
}
MAIN_GT1:
fclose( stream );
} |
程序创建一个名为 fseek.txt 的空文件,然后向这个文件里写“123”三个字符,然后想把“23”改为“34”,可是为什么循环不停而且文件内容象下面不断增加?
134444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444443
原来windows的fwrite库函数有个严重的BUG,这样做就没事了:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main( void )
{
FILE *stream;
char ch = '1';
char buf[60] = "123";
stream = fopen( "./Debug/fseek.txt", "w+" );
if( stream == NULL )
{
printf( "The file fseek.out was not opened\n" );
return;
}
if(strlen(buf) != fwrite(buf, 1, strlen(buf), stream))
{
printf( "Error!\n" );
goto MAIN_GT1;
}
rewind( stream );
printf( "Position 1-----: %ld\n", ftell( stream) );//[]
while(1 == fread(&ch, 1, 1, stream))
{
printf( "Position 3: %ld, ch = %c\n", ftell( stream), ch );//[]
if(0 != fseek(stream, -1, SEEK_CUR))
{
printf( "Error! fseek != 0 \n" );
goto MAIN_GT1;
}
ch++;
if(1 != fwrite(&ch, 1, 1, stream))
{
printf( "Error! fwrite != 0 \n" );
goto MAIN_GT1;
}
if(0 != fseek(stream, 0, SEEK_CUR))
{
printf( "Error! fseek != 0 \n" );
goto MAIN_GT1;
}
}
MAIN_GT1:
fclose( stream );
} |
[ 本帖最后由 tgbvc 于 2008-2-20 16:49 编辑 ] |
|