c - 在C中的子进程中读取文件

标签 c file process pipe fork

基本上,我正在尝试读取一个文件并查看是否有任何行与我创建的子进程中的给定字符串相匹配。然后将答案传输到打印出来的父进程。我的问题是我的代码只有在我输入 txt 文件的最后一行时才有效。任何其他行都被报告为文件中不存在。

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>

void Login()
{
char name[20];
int pfd[2];
pid_t pid;

pipe(pfd);

if((pid=fork()) == -1)
{
 exit(1);
}

if (pid==0)
{
 close(pfd[0]);
 FILE *fp = fopen("loginuser.txt", "r");
 printf("name:");
 scanf("%s", name);
 int ok = 0;
 if (fp!=NULL)
{
 char line[20];
 while (fgets(line,20,fp) !=NULL)
{
 if (strcmp(name,line)==0) ok = 1;
}
 fclose(fp);
}
 char s1[]="logged in!";
 char s2[]="Not found!";
 if(ok==1) write (pfd[1],s1,strlen(s1));
 else write(pfd[1],s2,strlen(s2));
 exit(0);
}
else
{ 
 close(pfd[1]);
 int n;
 char reada[20];
 n=read (pfd[0],reada,sizeof(reada));
 printf("%s",reada);
}
}

int main (int argc, char *argv[])
{
 Login();
 return 0;
}

登录用户.txt

aaabs
fas
ttt
aloo

在这种情况下,输入 aloo 以外的任何内容都不会给出正确的结果。在 parent 打印一些东西后,我还有两个额外的字符。 知道我做错了什么以及为什么它没有按预期工作吗?

最佳答案

Fgets 在您的行中返回 endtrail 字符,这意味着您实际上是在将 aaabsaaabs\n 进行比较,因此 strcmp 失败。 如果你这样做:

      while (fgets(line,20,fp) !=NULL)
        {
          size_t i = strlen(line) - 1;
          if (line[i] == '\n')
            line[i] = '\0';

          if (strcmp(name,line)==0)ok = 1;
        }

它会用 '\0' 移除每个 '\n',从端线清理缓冲区。

关于c - 在C中的子进程中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451594/

相关文章:

c# - 将 C 结构移植到 C#

c++ - 如何使用 ifstream 从文件中正确读取无符号整型变量?

c - Sem_post() 无法正常工作,既不会增加信号量的值,也不会解锁附加到该信号量的进程

c - 斐波那契数列偶数项之和小于 400 万

c - 错误 "Function was not declared in this scope",即使它是

linux - 请帮助我使用 linux 终端检查主机文件中的重复项

python - 如何实现tail -F的pythonic等价物?

python - 如何在了解时间常数和稳态值的 gekko 中构建过程模拟器

batch-file - 进程结束后执行命令的批处理文件

C 编程错误 - 计数器已定义?