Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

Cannot open a file in C- Error in opening a file in C

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
");
    }
        printf("Reading..
");
  fclose(file[1]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When using an IDE (and since you have a cmake-build-debug directory then I guess you're using the CLion IDE) the default working directory is seldom what is expected. And for CLion it seems it's not where you currently store the data.txt file. (I don't remember the default for CLion.)

Assuming CLion, you need to edit your "Run/Debug Configuration" for the program (menu "Run" and item "Edit Configuration"), and set the "Working Directory" to where you have the data.txt file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...