首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

文件读写的一个有关问题

2013-12-28 
文件读写的一个问题我打算将如下两行读到一个文件里:x [1 9 25 49 81 121 169 225 289 361 441 529 625

文件读写的一个问题
我打算将如下两行读到一个文件里:
x = [1 9 25 49 81 121 169 225 289 361 441 529 625 729 841 961 1089 1225 1369 1521];
y = [1222 1486 1752 2024 2301 2581 2865 3152 3439 3730 4025 4324 4629 4941 5261 5589 5925 6269 6621 6981];
读写的代码如下:


//实际上就是每次保存当前写入的位置,下次写入的时候直接跳到该位置
//用了ftell,fseek和fgetpos, fsetpos均没有达到想要的效果
//无论是文本文件写入还是二进制文件写入,结果都是一样的,不正确的结果
FILE *file = fopen( "z:\\代码\\data.txt", "w+t" );
//long tmp_ptr1, tmp_ptr2;
fpos_t pos_1, pos_2;

//先写第一行的数据
rewind( file );
fprintf( file, "x = [" );
//tmp_ptr1 = ftell( file );
fgetpos( file, &pos_1 );

//在写第二行的数据
 fprintf( file, "\n" );
 fprintf( file, "y = [" );
// tmp_ptr2 = ftell( file );
fgetpos( file, &pos_2 );

for ( m = 0; m < 20; m++ )
{
    n = 2 * m + 1;

//写第一行的数据
    rewind( file );
//fseek( file, tmp_ptr1, SEEK_SET );
    fsetpos( file, &pos_1 );
    fprintf( file, "%d ", n * n );
//tmp_ptr1 = ftell( file );
    fgetpos( file, &pos_1 );

//写第二行的数据
    rewind( file );
// fseek( file, tmp_ptr2, SEEK_SET );
    fsetpos( file, &pos_2 );
    fprintf( file, "%d ", minkowski_pxlCnt );
// tmp_ptr2 = ftell( file );
    fgetpos( file, &pos_2 );
}

rewind( file );
//fseek( file, tmp_ptr1, SEEK_SET );
fsetpos( file, &pos_1 );
fprintf( file, "\];" );

rewind( file );
//fseek( file, tmp_ptr2, SEEK_SET );
fsetpos( file, &pos_2 );
fprintf( file, "];" );

fclose( file );

结果打开文件一看,发现写成了这样:
x = [1 9 25 49 81 121 169 225 289 361 441 529 625 729 841 961 1089 1225 1369 1521 ];61 5589 5925 6269 6621 6981 ];
[解决办法]
请检查每个函数的返回值!

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.


[解决办法]
y = [1222 1486 1752 2024 2301 2581 2865 3152 3439 3730 4025 4324 4629 4941 5261 5589 5925 6269 6621 6981];
对于上面信息,你只保存了红色标记的部分
自己分析一下是不是文件指针那里处理处问题了

热点排行