|

楼主 |
发表于 2007-2-26 23:00:13
|
显示全部楼层
Post by xiexiecn
这个程序很多问题,首先第一个if判断文件打开失败应该return,否则下面会使用空指针;sprintf(p, "")是干什么,初始化p为空吗,这种写法不好,有点莫名其妙,不如p[0] = '\0',或者strcpy(p, "")来得直接;c!=''\r'',双引号可以编译通过吗,字符如何和字符串比较;fgetc的返回值请参看函数说明,如下;内循环while也是,要获取一行,不如fgets好,你这样处理效率也太低了吧。
fgetc and _fgetchar return the character read as an int or return EOF to indicate an error or end of file.
贴上fgets函数看看吧,没有用过呢
fgets(由文件中读取一字符串)
相关函数
open,fread,fscanf,getc
表头文件
include<stdio.h>
定义函数
har * fgets(char * s,int size,FILE * stream);
函数说明
fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,直到出现换行字符、读到文件尾或是已读了size-1个字符为止,最后会加上NULL作为字符串结束。
返回值
gets()若成功则返回s指针,返回NULL则表示有错误发生。
范例
[php]
#include<stdio.h>
main()
{
char s[80];
fputs(fgets(s,80,stdin),stdout);
}
[/php]
执行
this is a test /*输入*/
this is a test /*输出*/
顺便贴下我改正后的部分:
[php]
#include <stdio.h>
int main()
{
FILE *fp;
char p[256];
int c;
if ((fp = fopen("m.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
return 0;
}
while (!feof(fp))
{
strcpy(p,"");
fgets(p,256,fp);
printf("p=%s", p);
}
fclose(fp);
return 0;
}
[/php]
还想问下,p要赋初值吗?strcpy(p,"");就可以了吗?
如果是: char *p;行不行呢?怎样赋初值呢? |
|