无法在 C 中打开文件 - 在 C 中打开文件时出错 [英] Cannot open a file in C- Error in opening a file in C

查看:69
本文介绍了无法在 C 中打开文件 - 在 C 中打开文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打开文件的主要函数位于project"目录中.然后我有一个cmake-build-bug"目录(位于project"目录中),data.txt"文件所在的位置.我想阅读它,但由于某种原因,它一直在写入 Error to open file.我从来不明白如何写出正确的文件路径.或者还有其他问题导致错误?

 FILE *file[2] ;char *fileName2 = "data.txt";文件[1] = fopen(fileName2, "r");如果(文件 [1] == NULL){printf("打开文件出错\n");}printf("正在阅读..\n");fclose(文件[1]);

解决方案

根据

The main function that opens the file is located in "project" directory. Then I have a "cmake-build-bug" directory( located in "project" directory) where is "data.txt" file located. I want to read it, but for some reason it keeps wrinting Error to open file. I never understand how to write the correct path to the file. Or is there another problem that gives the error?

  FILE *file[2] ;
  char *fileName2 = "data.txt";
    file[1] = fopen(fileName2, "r");
    if (file[1] == NULL){
        printf("Error to open file\n");
    }
        printf("Reading..\n");
  fclose(file[1]);

解决方案

According to http://man7.org/linux/man-pages/man3/fopen.3.html the first param is a pathname and not a filename as a lot of people believe. Let's assume that c:\your_ project\a_subfolder\data.txt is the pathname, just remember that \ is an escape char, so I believe in general, when the file is in a different folder, you could try char *fileName2 = "c:\\your_ project\\a_sub_folder\\data.txt"

Just keep an eye on the real path of the file. Cmake tends to create folders to put the executable elements in. For example, look at this case where the file was in a local folder and cmake created a copy in the debug folder.

这篇关于无法在 C 中打开文件 - 在 C 中打开文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆