【发布时间】:2014-12-14 20:12:02
【问题描述】:
所以我想编写一个程序,它会打印出包含文件中某个单词的文本行。例如如果我正在寻找一个单词“linux”,它会打印出来
2 台计算机称为 linux00、linux01 和 linux02。
5 经理,” 说linux00。 “你好 linux00,”说
7 来找我们?”说 linux01. “好吧,”
10 linux02. “你们都会成为 拔掉电源,”说
12 goooooooooooooo..." linux00 说。
来自story.txt:
从前有三个小
计算机调用 linux00、linux01 和 linux02。
有一天,漂亮的电脑管理员 进入了
Linux 实验室。 "你好漂亮的电脑
经理,” 说linux00。 “你好 linux00,”说
漂亮的电脑管理员。 “给你带来了什么
来看我们?” linux01 说。“嗯,”
不错的电脑管理员,“我有坏消息,而且
我很好 新闻。” “什么坏消息?”说
linux02. “你们都会成为 拔掉电源,”说
漂亮的电脑管理员。 “这是什么
goooooooooooo..." linux00 说。
这是我的代码:
#include<stdio.h>
#include <stdlib.h>
#define ARR_LEN 100
int getLine(FILE * fin,char a[],int n)
{
int find = contains("linux", 5, a, ARR_LEN);
int count;
int i;
i = 0;
char c = getc(fin);
while(c != '\n')
{
a[i] = c;
// printf ("%c", a[i]);
//i = 0;
if (a[i] == EOF){
return EOF;
}
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
i = i + 1;
}
if(a[i]=='\n')
{
if ((i - 1) > ARR_LEN) {
printf("warning msg: length is over array bounds\n");
}
// printf("length of line is: %d\n", i - 1);
//printf("%c", a[i]);
i = i + 1;
//printf("\n");
return i - 1;
}
}
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;
for(i = 0; i < n; i++) { // go through each character of the source string
int targetIndex = 0;
int j;
/*check if the preceding characters of the source string are a substring
that matches the target string*/
for(j = i; j < n && targetIndex < m; j++) {
if(target[targetIndex] == source[j]) {
targetIndex += 1;
if(targetIndex == m) { // the 'target' has been fully found
flag = 1;
break;
}
}
else
{
break;
}
}
if(flag == 1) // 'target' is already found, no need to search further
{
break;
}
}
return flag;
}
main(int argc,char ** argv)
{
setbuf(stdout,NULL);
char a[ARR_LEN];
FILE * fin;
if(argc<2){
printf("wrong number of arguments\n");
exit(0);
}
fin = fopen(argv[1], "r");
if (fin == NULL) {
printf("Cannot open %s\n", fin);
exit(0);
}
int t = 0;
int j = 0;
int find = contains("linux", 5, a, ARR_LEN);
while (j != EOF)
{
t = t + 1;
printf("%d ", t);
j = getLine(fin,a,ARR_LEN);
printf("\n");
}
fclose(fin);
}
getLine 函数没问题,它打印出一个前面有行号的文本,一切都很好。但问题出在这个
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
部分,如果“包含”在该行中找到匹配项,我希望程序仅打印出该行。
感谢您的帮助,抱歉发了这么长的帖子!
【问题讨论】:
-
看起来
contains("linux", 5, a, ARR_LEN);在getLine(fin,a,ARR_LEN);之前而不是之后调用。 -
如果你在 main() 中谈论那个,我只是忘了删除它,但它并没有改变任何东西
-
次要:
char c应该是int c。任何像if (a[i] == EOF){中的EOF 测试都应该在分配给a之前进行。 EOF 是一个条件,而不是char。