|

- 帖子
- 7
- 精华
- 0
- 积分
- 22
- 阅读权限
- 10
- 在线时间
- 1 小时
|
3楼
发表于 2007-4-26 22:26
| 只看该作者
回复 #2 danvy 的帖子
以下程序在VC6中可以正确运行,但在unix上运行不正确,请大家指正:
cat main.c
#include <stdio.h>
#include <string.h>
#include "getcfg.h"
void main(void)
{
char fn[10] = "test.txt";
char line[100];
int num=0;
int len=0;
FILE * p;
p = fopen( fn, "r" );
while( !feof(p) )
{
memset( line, 0, 100 );
len = get_num_of_line( p );
num = get_line( p, line );
printf("%d:%s\n", len,line );
}
}
-----------------------------------------------
cat getcfg.h
int get_line( FILE *p, char *line );
int get_num_of_line( FILE *p );
-----------------------------------------------------
$ cat getcfg.h
int get_line( FILE *p, char *line );
int get_num_of_line( FILE *p );
-bash-3.00$ cat getcfg.c
#include<stdio.h>
/*
FILE *p : input argument
char *line: output argument
return value:
-1: end of file
0: a blank line
>0: num of characters
*/
int get_line( FILE *p, char *line )
{
unsigned char c;
int i=-1;
while( !feof(p) )
{
c=fgetc( p );
if( c == 255 ) // if end of file
{
return i; // then return -1
}
else if( c == '\n' ) // if it's end of line
{
c = 0;
break;
}
else
{
line[++i] = c;
}
}
i = i + 1;
line = c;
return i;
}
int get_num_of_line( FILE *p )
{
unsigned char c;
int i=0;
int offset=0;
int where=0;
where = ftell( p );
printf("Start at:%d\n", where );
while( !feof(p) )
{
c=fgetc( p );
if( c == 255 )
{
break;
}
else if( c == '\n' )
{
offset=-2;
break;
}
else
{
i++;
}
}
offset -= i;
fseek( p, offset, SEEK_CUR );
printf("Offset is %d\n", offset );
where = ftell( p );
printf("End at:%d\n", where );
printf("Line length is %d\n", i );
return i;
}
-----------------
cat test.txt
this is a text file
in the second line
This is the 3rd line!
--------------------
运行结果是:
Start at:0
Offset is -21
End at:61
Line length is 19
19: |
|