如何使用这段代码把下面那个staff.dat文件读入内存,并显示出来呢?
char readline(FILE * stream){
char *line = Null;
char buffer[Buffer_LEN];
int new_length;
char *dest;
int finished = 0;
while (fgets(buffer,Buffer_LEN,stream)){
if (buffer[strlen(buffer)-1] == '\n'){
buffer[strlen(buffer)-1] = '\0';
}
if (strlen(buffer) < BUFFER_LEN-1){
finished = 1;
}
#if DEBUG
printf("Read: [%s] (%d)\n", buffer, strlen(buffer));
#endif
if (line == NULL) {
new_length = strlen(buffer) + 1;
line = (char *) malloc (new_length);
dest = line;
}else {
new_length = strlen(line) + strlen(buffer) + 1;
line = (char *) realloc(line, new_length);
dest = line + strlen(line);
}
if (line == NULL) {
return NULL;
}
strcpy(dest, buffer);
#if DEBUG
printf("Line: [%s] (%d)\n", line, strlen(line));
#endif
if (finished) {
break;
}
}
#if DEBUG
if (line) {
printf("Entire line: [[%s]]\n", line));
#endif
return line;
}
staff.dat文件内容如下:
34:JVT:Crimp and Perm
65:NAH:Manicurist
21:CJW:Non Surgical Facelifts
78:MWJ:Pedicures
7:PWG:Ear Piercing
15:JAS:Leg Waxing
96:AMG:Bikini Waxing如下:
问题点数:50、回复次数:7Top
1 楼imRainman(雨人)回复于 2004-12-03 07:15:09 得分 0
FILE *f ;
f = fopen("staff.dat", "r") ;
readline(f) ;
fclose(f) ;
Top
2 楼bylmy()回复于 2004-12-03 21:21:37 得分 0
那么再显示出来呢?Top
3 楼masse(当午 http://blog.sina.com.cn/xukf)回复于 2004-12-03 22:03:31 得分 0
你的程序的定义应该是char* readline(FILE * stream)
因为你最后返回的line是char*的,不是char
你试试char* line = readline(f)
printf("%s",line);
不知道行不行,没有调试,试试吧Top
4 楼imRainman(雨人)回复于 2004-12-04 09:25:38 得分 0
最简单的方法:在程序的最前面加上:#define DEBUG
或者把所有的:#if DEBUG 和 #endif去掉。Top
5 楼bylmy()回复于 2004-12-05 08:46:35 得分 0
我在楼顶给出的这段代码是一次读入一行字符进入内存,
34:JVT:Crimp and Perm
现在如果我需要这样显示一行,
fprintf(stream, "%s(%d) providing %s has the following appointment:\n",
staffs[i].name, staffs[i].pid, staffs[i].occupation);
如何实现?
例如:34:JVT:Crimp and Perm这一行输出后为
JVT(34) providing Grimp and Perm has the following appointment
其中staffs[i].name=JVT,staffs[i].pid=34,staffs[occupaton]=Grimp and Perm.Top
6 楼bylmy()回复于 2004-12-05 20:54:52 得分 0
那位大大给帮忙看看那Top
7 楼imRainman(雨人)回复于 2004-12-05 23:41:47 得分 50
#include <stdio.h>
int readline(FILE *file, char *buff, int length)
{
int count = 0 ;
long pos ;
if (length == 0) return 0 ;
pos = ftell(file) ;
fgets(buff, length, file) ;
if (buff[strlen(buff) - 1] != '\n')
{
fseek(file, pos, SEEK_SET) ;
return 0 ;
}
while (*buff != '\n')
{
if (*buff == ':') *buff = 0, count++ ;
buff++ ;
}
*buff = 0, count++ ;
return count ;
}
void main( )
{
char *buff = 0 ;
char *p = 0 ;
int size = 20 ;
int rtn = 0 ;
FILE *file ;
long fend ;
buff = (char *)malloc(size) ;
file = fopen("staff.dat", "r") ;
fseek(file, 0, SEEK_END) ;
fend = ftell(file) ;
fseek(file, 0, SEEK_SET) ;
while (ftell(file) != fend)
{
while ((rtn = readline(file, buff, size)) == 0)
{
free(buff) ;
size += 20 ;
buff = (char *)malloc(size) ;
}
if (rtn >= 3)
{
p = buff + strlen(buff) + 1 ;
printf("%s(%s) providing ", p, buff) ; p += strlen(p) + 1 ;
printf("%s has the following appointment\n", p) ;
}
} ;
fclose(file) ;
free(buff) ;
getch( ) ;
}Top




