【发布时间】:2015-04-16 21:37:21
【问题描述】:
我正在尝试编写代码以逐行搜索文件中的单词并打印包含该单词的行。
fgets 和 getline 函数似乎不起作用。
void FindWord(char *word , char *file){
char *line ;
line = (char*)malloc(1024) ;
int fd ;
fd = open(file , O_RDONLY );
while (fgets(line , sizeof(line) ,fd )!= NULL)
{
if (strstr(line , word )!= NULL)
{
printf("%s",line);
}
}
}
【问题讨论】:
-
我可以在 open() 中使用哪些函数来作为 fgets() 使用?
-
1) 使用 fopen() 2) 关于 malloc(),在 C 中不要强制转换返回值 3) 关于 malloc() 始终检查 (!=NULL) 返回值以确保操作成功. 4) 始终检查 (!= NULL) 任何 open/fopen 函数调用的返回值。 5) 使用 fopen(filename, "r") 然后 fgets 和 getline 将工作。
-
请阅读您在代码中使用的那些函数的手册。例如,open() 返回一个小整数,但 fgets 和 getline 需要一个指向文件描述符的指针。
-
'sizeof(line)' 其中行声明为:'char *line;'将返回 4,而不是 malloc() 分配的字节数
-
@user3629249,对于您的第一条评论,第 (1) 点:
open使用起来还不错。fopen也在其中使用open。fopen只是一个库调用,open是一个系统调用。两者都做同样的工作。只是fopen更容易使用。但是你不能说fopen比open好。所以你的观点是错误的。
标签: c file search fgets strstr