请教高手文件读取的一个问题???
我有一个文本文件,是按照“数字 字符串 字符串 字符串(回车)”的格式编写的,用fgets函数读取时,若格式完全正确,则没问题,但是如果在文件末尾有几个回车键或/和空格键,(从表面上看不出格式错误),那么读取就回发生错误,请问怎么把末尾多余的回车空格去掉或不去读,(我用的是feof来结束循环)????
另外如果格式错误,程序回发生异常,我想自己捕捉这个异常,应该怎么实现,他的异常类型是什么,希望哪位高手能提供源代码??多谢了!!!!!!!!!!
[解决办法]
使用fgets和sscanf可以解决上述问题,代码如下:
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
void main( void )
{
int n;
char s1[81];
char s2[81];
char s3[81];
int count;
char buffer[256];
stream = fopen( "a.txt ", "r+ " );
if( stream == NULL )
printf( "The file fscanf.out was not opened\n " );
else
{
while (! feof(stream))
{
//先取出每一行的数据
fgets(buffer, 256, stream);
//如果为空行则跳过
if (*buffer == ' ' || *buffer == '\r ' || *buffer == '\n ')
{
continue;
}
//将每一行的数据分解,count用来记录偏移
count = sscanf( buffer, "%d ", &n );
count += sscanf( buffer+count, "%s ", &s1 );
count += sscanf( buffer+count, "%s ", &s2 );
count += sscanf( buffer+count, "%s ", &s3 );
//输出每一行的数据
printf( "%d ", n );
printf( "%s ", s1 );
printf( "%s ", s2 );
printf( "%s\n ", s3 );
}
fclose( stream );
}
system( "pause ");
}