【发布时间】:2016-01-20 15:19:13
【问题描述】:
该程序读取一个文本文件“hello.txt”并查找其中出现的字符串 w 并打印行号和整行。它还打印字符串 w 在文件中出现的次数。程序编译没有错误,代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
int main() {
int fd;
char c;
char str[152];
int i = 0, j = 0;
int bytesread;
int flag = 1;
int found = 0;
int line = 1;
int foundflag = 1;
char w[] = {'h', 'e', 'l', 'l', 'o'};
int len = strlen(w);
if ((fd = open("hello.txt", O_RDONLY, 0)) != -1) { //if 1
bytesread = read(fd, &c, 1);
str[j] = c;
j++;
if (bytesread != -1) { //if 2
while (bytesread != 0) { //while
if (c == '\n')
line++;
if (c == w[i]) { //if 3
i++;
flag = 0;
} else if (flag == 0 || i == len) //end of f3
{ // else 3
i = 0;
flag = 1;
}// end of else 3
else if (flag == 1) {
while (read(fd, &c, 1)) {
str[j] = c;
j++;
if (c == ' ')
break;
if (c == '\n') {
line++;
break;
}
}
}
bytesread = read(fd, &c, 1);
str[j] = c;
j++;
if ((c == ' ' || c == '\n') && flag == 0 && i == len) {
found++;
foundflag = 0;
printf("w was found in line %d.\n", line);
}
if ((c == '\n')&&(foundflag == 0)) {
for (j = 0; str[j] != '\n'; j += 5) {
printf("%c", str[j]);
if (str[j + 1] != '\n')
printf("%c", str[j + 1]);
else {
j++;
break;
}
if (str[j + 2] != '\n')
printf("%c", str[j + 2]);
else {
j += 2;
break;
}
if (str[j + 3] != '\n')
printf("%c", str[j + 3]);
else {
j += 3;
break;
}
if (str[j + 4] != '\n')
printf("%c", str[j + 4]);
else {
j += 4;
break;
}
}
for (; str[j] != '\n'; j++)
printf("%c", str[j]);
printf("\n");
j = 0;
} else if (c == '\n')
foundflag = 1;
} //end of while
printf("w has occured %d times.\n", found);
} else //end of if 2
printf("couldn't read file.\n");
} else //end of if 1
printf("Couldn't open file for read.\n");
close(fd);
} //end of main
这是终端中的输出:
w was found in line 1.
hello
w was found in line 2.
w was found in line 6.
hello world
hellooooo
w has occured 3 times.
这里是“hello.txt”的内容:
hello
hello world
hallo
I'm here
we're here
hello
hellooooo
输出中打印的行数是 1,2 和 6,但输出应该是这样的:
w was found in line 1.
hello
w was found in line 2.
hello world
w was found in line 6.
hello
w has occured 3 times.
【问题讨论】:
-
TL;博士!请将代码缩小到您遇到问题的部分。或者更好的是,请发送Minimal, Complete, and Verifiable Example 向我们展示。
-
你有什么理由不使用
strncmp来测试w的出现吗? -
但在我做过阅读的部分中,我几乎立即看到了一些未定义的行为。您将数组
w视为字符串,但您似乎忘记了C 中的字符串是终止的,而数组w没有此终止符,因此当您例如致电strlen它将超出范围,您将拥有 UB。 -
使用
char w[]="Hello";而不是char w[]={'h','e','l','l','o'};。这更具可读性并且(在您的情况下最重要),它添加了一个零终止符。见之前的 cmets。 -
你忘了问问题。你的问题是“你如何调试 C 代码?”
标签: c printf output system-calls