Where to put files so C program can access them? - c

I'm trying to open files in a C program, but I am unsure where to place the files I want to open (as in which directory). Here is the code, but I really just need to know where to place the file I want to open with fopen().
FILE *fileptr;
fileptr = fopen("QuizQuestions.txt", "r");
if (fileptr == NULL) {
printf("Unable to open file.");
}
Any help is appreciated!

If you don't use an absolute pathname in your code, paths are interpreted relative to the working directory of the user when they run the program. So for your program, the user should put the file in their current directory.
The location of the program itself is irrelevant. If you want to get the location of the program, you see this question:
How do I find the location of the executable in C?
You can then concatenate the directory with the filename.

You need to keep files where source code file is placed.Otherwise, you need to give absolute path.

Related

Accessing a different drive in c

I want to scan a directory, checking for JPEG-files (i.e. the combination of the first few bytes) and copying them to another drive. I successfully tested that program and it screens documents. However, I cannot access a whole directory (e.g. my accidentally erased SD-Card in D:/).
Here is how I tried to access it:
// remember the path from the command line
char *path = argv[1];
// open the path (preferably "D:\" - which is my SD-Card ;))
FILE *inptr = fopen(path, "r");
if (inptr == NULL)
{
fprintf(stderr, "inputfile could not be read\n");
return 1;
}
The output is "inputfile could not be read" - which is why I am quite confident that the error is right there. Do I need to address a directory differently? E.g. by using a pointer to the first bit of the drive?
I am a beginner - so please be gentle while laughing. ;)
Thank you very much!
Marcel
'fopen()' cannot open an entire directory or drive, it can only open a specific path. However, there are ways to accomplish the task of listing all files in a directory. This answer already contains some pertinent information.
Since you can already open files,you could adapt the loop shown there to perform the operation.
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
if (/*Check whether file has the .jpg extension or another test*/)
{
// perform your copy operation on the file
}
}

Open file in a different directory

I have to do a simple task. I have to open a file which is in a directory. I have the .c file in src, when I compile I move the programs (a.out) in the a bin directory. I want to read a file in the directory asset. All these folders are in a main folder.
If I do this
FILE* fp = fopen("../asset/team_list", "r");
it won't open the file. Why can't I open the file in that directory?
guess you forgot to put the extension of your file
FILE* fp = fopen("../asset/team_list.doc", "r");
Find what error you get using perror/explicit mention of error message and expect a possible reply from stackoverflow.
Make sure you are pointing out to the correct directory where the file is present from the PWD from where your program is being executed.
Relative paths are relative to the current working directory of the process, which might not be the same location as the binary file. So, if you are in /home/user/ and you run ./project/bins/my.exe then your current working directory is /home/user/, relative paths need to be relative to that location.
You can try a few things to help with this issue. First, after the failed open you could examine errno to see why the open failed, is it permissions, invalid path?
Alternatively you might have access to the strace program, this traces system calls, like open from your application, and will allow you to see the failed system call. Try strace ./project/bins/my.exe, you'll see a lot of output, dig through this looking for the failed open call, and try to figure out why this is failing, again the errno will be included in the trace to help understand the failure.
Lastly, you could just add a call to getcwd to your program and print the result (as a debugging aid), this places the current working directory into a buffer, something like this:
char buffer [PATH_MAX + 1];
getcwd (buffer, PATH_MAX + 1);
printf (buffer);

How to read file from local directory path

I have one function which reads file and does the conversion part.
fp=fopen("newfile.txt","r");
Here i have copied this newfile.txt in project file and compiling in VC++ 2008 IDE.It works fine
I would like to read the file from a local drive directory path.is it possible to read the files from local drive.how to mention the path.If so please mention any example.
one more thing If i want to read all the files in that particular folder with out changing the name of text files in the above code. Suggest me any thing to do.
I dont want to change the file name manully in the code
You could use an absolute path to your file:
FILE* fp = fopen("c:\\your_dir\\your_file.txt", "r");
if(fp) {
// do something
fclose(fp);
}
or a relative path, assuming your file is located in c:/etc and your executable is located in c:/etc/executables:
FILE* fp = fopen("..\\your_file.txt", "r");
if(fp) {
// do something
fclose(fp);
}
I think you can use first program argument. It is a string containing path of executable. You can access it by usingint main(int argc, char *args[]) instead of int main(). The args[0] contains what you need. Just take a substring of it, to get the path and concatenate it with your filename.

open file dir problem

I'm running an Linux OS and trying to open file in C compiler like this :
file = fopen ("list.txt", "r");
but the file is not opend!
and when i put the full path like this :
file = fopen ("/home/rami/Desktop/netfilter/list.txt", "r");
it is working!
why the first example is not working?
the list.txt is in the same directory of the c file
thanks.
It's not the directory of the C file that matters, it's your current working directory that does. Try
cd /home/rami/Desktop/netfilter
before running the executable.
Do you know WHY the file didn't open?
Always check the return value of fopen() (and most other functions) and report back a readable error.
file = fopen("file.txt", "r");
if (!file) {
perror("file open");
exit(EXIT_FAILURE);
}
I see you've already found out what your problem is, but the above is a suggestion for the future (and to change your current project)
Is the executable also in the same dir as that of list.txt?
Edit: Actually that doesnt matter. It's the current working dir as per the other answer.

How to open a text file that's not in the same folder?

Since C it's not a language I am used to program with, I don't know how to do this.
I have a project folder where I have all the .c and .h files and a conf folder under which there is a config.txt file to read. How can I open that?
FILE* fp = fopen("/conf/config.txt", "r");
if (fp != NULL)
{
//do stuff
}
else
printf("couldn't open file\n");
I keep getting the error message. Why?
Btw, this only have to work on windows, not linux.
Thanks.
The easy way is to use an absolute path...
my_file = fopen("/path/to/my/file.txt", "r");
Or you can use a relative path. If your executable is in /home/me/bin and your txt file is in /home/me/doc, then your relative path might be something like
my_file = fopen("../doc/my_file.txt", "r");
The important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your /tmp directory and you ran /home/me/bin/myprog, it would try to open /tmp/../doc/my_file.txt (or /doc/my_file.txt) which would probably not exist.
The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to fopen. The simplest example would be to just use argv[1] from main's parameters, i.e.
int main(int argc, char **argv)
{
FILE *my_file = fopen(argv[1], "r");
/* ... */
return 0;
}
Of course, you'll want to put in error checking to verify that argc > 2, etc.
You're probably going to want to look into the dirent family of routines for directory traversal.
The location of your .c and .h files is not really the issue; the issue is the current working directory when you run your executable.
Can you not pass in the full path to the fopen() function?

Resources