关于在文本文件里查找字符串的简单问题!
想在一个指定的文本文件里查找指定的字符串,查找成功以后返回该字符串所有行。
写了一下,可运行的时候老是有内存错误!请大家帮看一下,谢谢!
FILE *fp;
char array[256], ch, *buf[50], *ptr;
int i = 0, j = 0, n;
if ((fp = fopen("program.c", "r")) == NULL)//打开一个源代码文件program.c
{
fprintf(stderr, "Error open the file.");
exit(1);
}
while ((ch = fgetc(fp)) != EOF)//一直读到文件尾
{
array[i] = ch;
i++;
if (ch = 0)//读完一行,把字符串复到指针数组
{
i = 0;
if ((buf[j] = (char *)malloc(array[i-1])) == NULL)
{
fprintf(stderr, "Error Memory allocate!");
exit(1);
}
strcpy(buf[j], array);
j++;
continue;
}
}
for (j = 0; j < 50; j++)//在指针数组里面查找printf,如果找到返回所在行的行数
{
ptr = strstr(buf[j], "printf");
if (ptr != NULL)
{
n++;
}
free(buf[j]);
}
printf("The line is %d", n);
问题点数:20、回复次数:2Top
1 楼yingge(...木脑壳...)回复于 2006-07-03 09:49:30 得分 20
array[i] = ch;
i++; //这里会不会数组越界,如果一行超过255字符怎么办?
if (ch = 0)//ch=0? 什么语法,那不是永远false了吗?判断一行是不是应该这样 if(ch=='\n')
buf[j] = (char *)malloc(array[i-1]) //这又是什么意思,分配array[i-1]这里存储的数这么多字节给buf[j],是不是应该这样 buf[j] = (char *)malloc(i);
strcpy(buf[j], array); //怎么复制啊?是不是应该这样 strncpy(buf[j],array,i);
//然后array不用清零?是不是应该加上下面这句
bzero(array,sizeof(array));
continue; //这个continue有何意义?
//打开完了文件句柄也不关闭?
fclose(fp);
错误好多,也许还有,自己努力一下吧,最后要说的是,读文件一行怎么这么麻烦?!!
直接用fgets函数不好吗??!!
Top
2 楼haha168_2002(啥时候我能成为高手啊?)回复于 2006-07-03 16:00:21 得分 0
解决了,谢谢啊,更改以后的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 80
int main(void)
{
char buf[MAX];
int count = 0;
FILE *fp;
if ((fp = fopen("program.c", "r")) == NULL)
{
fprintf(stderr, "Error open the file.");
exit(1);
}
while (!feof(fp))
{
fgets(buf, MAX, fp); //读取一行文本,放入指定内存
count++;
if ((strstr(buf, "count")) != NULL)//如果文本中存在内容count,打印出所在行
printf("The \"count\" is in the %d line.\n", count);
}
fclose(fp);
system("pause");
return 0;
}Top




