C无法使用变量打开文件

标签 c linux

我需要打开位于桌面 (Linux) 上的文件。如果我在 fopen() 函数中将位置写为字符串,它会起作用,但如果我将它作为变量传递,它就不起作用。这是我的代码:

fp = fopen(readPathToFile, "r");
if (!fp){
       printf("Failed to open text file\n");
       exit(1);
}
else{
      fscanf(fp,"%s",line);
      printf("File read: %s",line);
}

如果我这样写,它会显示文件的内容:

fp = fopen("home/user/Desktop/test.txt", "r");
    if (!fp){
           printf("Failed to open text file\n");
           exit(1);
    }
    else{
          fscanf(fp,"%s",line);
          printf("File read: %s",line);
    }

子进程打开文件。这是我的完整代码

   #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define READ  0
#define WRITE 1
int main ()
{
  pid_t pid;

  int mypipefd[2];
 id_t child_pid;
 char line[100];
 char *pathToFile[100];
 FILE *fp;
 char buff[255];
 /* create the pipe */
  if (pipe(mypipefd) == -1) {
    fprintf(stderr,"Pipe failed");
    return 1;
  }

 child_pid = fork () ;

    if (child_pid > 0) {
        printf("Introduceti locatia catre fisier:");
        fgets(pathToFile, 100, stdin);
        close(mypipefd[READ]);
        write(mypipefd[WRITE], &pathToFile, sizeof(pathToFile));
        close(mypipefd[WRITE]);
        printf("parent: write value : %s",pathToFile);
    }
    else if (child_pid < 0) {
        fprintf(stderr, "Fork failed");
        return 1;
    }
    else{
        char *readPathToFile[100];
        close(mypipefd[WRITE]);
        read(mypipefd[READ], &readPathToFile, sizeof(readPathToFile));
        close(mypipefd[READ]);
        printf("child: read value : %s",readPathToFile);
        fp = fopen(readPathToFile, "r");
        if (!fp)
        {
            printf("Failed to open text file\n");
            exit(1);
        }
        else{
            fscanf(fp,"%s",line);
            printf("File read: %s",line);
        }
    }
return 0;
}

最佳答案

您的编译器没有警告您类型不匹配

char *pathToFile[100];
fgets(pathToFile, 100, stdin);

(100 个字符指针数组与 100 个字符数组)?您是否关闭了警告?

另请注意,fgets 保留换行符。您的文件名可能不以换行符结尾。您应该将其替换为 NUL(零)字节。

通常您不需要调试器来跟踪这些。一点点 printf 调试可以创造奇迹。 :-)

关于C无法使用变量打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36385869/

相关文章:

c - 向路由器发送命令请求并以编程方式获得其回复

c - 这个数据报套接字有什么问题?

python - 没有这样的文件或目录 : 'gs' linux

c - 使用 gdb 检查调用者帧

linux - 管道命令的回显输出

c - C 中 main() 执行一半后输出消失

c - 在C中将数字写到没有printf的文件中?

linux - 在多个 shell 上运行 bash 脚本

c - 一月提醒程序中的strcmp()函数理解

在我自己的 shell 中创建后台进程