Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to open a file in C++, but the file cannot be found

Tags:

clion

I have an algorithm in C++ (main.cpp) and I use CLion to compile and run it. Algorithm would read strings from text file, but there is a mistake:

Could not open data.txt (file exists and placed in one folder with main.cpp)

How can I fix it and make this file "visible" to CLion?

like image 623
sayhello Avatar asked Jan 27 '15 21:01

sayhello


People also ask

How can a file be opened in C?

Opening a file is performed using the fopen() function defined in the stdio. h header file. The syntax for opening a file in standard I/O is: ptr = fopen("fileopen","mode");

What are the troubles with opening a file in C language?

There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file that doesn't exist.

When fopen () is not able to open a file it returns?

Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.


2 Answers

If you are using fopen or something similar and just passing "data.txt", it is assumed that that file is in the current working directory of the running program (the one you just compiled).

So, either

  1. Give a full path instead, like fopen("/full/path/to/data.txt"), where you use the actual full path

  2. (not preferable), Move data.txt to the directory where CLion runs its compiled programs from.

(for #2, here's a hacky way to get that directory)

char buf[1024]; // hack, but fine for this
printf("%s\n", getcwd(buf, 1024));
like image 91
Lou Franco Avatar answered Sep 17 '22 13:09

Lou Franco


  1. Run/Edit configurations...
  2. Select your application (on the lefthandside of the window)
  3. Specify Working directory
  4. Apply

Now you can fopen relatively from working directory.

like image 29
seawolf Avatar answered Sep 19 '22 13:09

seawolf