How do I read files in different directories using C?

73 Views Asked by At

I have been learning C as of late, and the one thing that keeps tricking me up is file reading/writing. My goal is to print out the contents of "words.txt" in my main file. I know how to do so when the words and main file are in the same folder, but not when they are in seperate folders as shown here. How do I do I read the file in this setting?SS of my file set up as example

I want to read the words.txt and print it out, in it's entirety, using C.

2

There are 2 best solutions below

0
RecReo On

Firstly, it doesn't matter where your main.c file is, only thing that matters is where you run the executable.

If your words.txt is from C:\Users\user\directory you can access it:

  • with words.txt from C:\Users\user\directory
  • with directory/words.txt from C:\Users\user
  • with ../words.txt from C:\Users\user\directory\src
  • and with C:\Users\user\directory\words.txt from anywhere

If you will be running the program only from VSCode, you can use Words Folder/words.txt, as VSCode executes commands from the base directory (so it's where Words Folder and Main Folder is).
But a more robust solution would be to specify the full path.

0
greg spears On

The answer is that you would include the path to the file and the file name as the first argument to fopen(). Here is some sample code on how to do that:

#include <stdio.h>

#if defined( _WINDOWS_ )  
    /* sample windows */
  const char filepath[] = "c:\\BCC55\\Bin\\bcc32.cfg";
#elif defined(__unix__)
    /*  sample unix */
  const char filepath[] = "/BCC55/Bin/bcc32.cfg";
#endif


int main()
{
    FILE *fh =  fopen(filepath, "r");

    if(!fh)
    {
        printf("Could not open %s\n", filepath);
    }
    return 0;
}