Walk relative path to fopen ()

I am trying to pass the relative path to fopen (), but it cannot find the file. I need this to work on Linux. File names (ex: t1.txt) are stored in an array. So I only need the "front" of the relative path.

Here is my code:

// Use strcat to create a relative file path char path[] = "./textfiles/"; // The "front part" of a relative path strcat( path, array[0] ); // array[0] = t1.txt // Open the file FILE *in; in = fopen( "path", " r " ); if (!in1) { printf("Failed to open text file\n"); exit(1); } 
+7
source share
4 answers
 in = fopen("path", " r "); 

Two errors:

  • You do not want to open a file with the literal name "path", you want the file whose name is in the variable path
  • argument mode is not valid; you want "r"

To make them right, do

 in = fopen(path, "r"); 
+6
source

First, you need to add a space in path to match the contents of array[0] in strcat , otherwise you will write past the highlighted area.

Secondly, you do not pass path to fopen because you enclosed the "path" in double quotes.

 char path[100] = "./textfiles/"; // Added some space for array[0] strcat( path, array[0] ); // Open the file FILE *in; in = fopen( path, " r " ); // removed quotes around "path" if (!in) { printf("Failed to open text file\n"); exit(1); } 
+5
source

Your problem has nothing to do with fopen and everything with C: strcat requires enough memory in the destination buffer for the entire line, but you provide enough memory for the start line. Poorly! By the way, using tools like valgrind will tell you about your illegal access, by the way.

Here's a naive solution:

 char buf[1000] = { }; strcat(buf, "./textfiles/"); strcat(buf, array[0]); // ... 
+2
source

path is large enough to contain the characters with which it was initialized. The size of the path should be increased. Allocate memory for path based on the file name to add:

 const char* dir = "./textfiles/"; const size_t path_size = strlen(dir) + strlen(array[0]) + 1; char* path = malloc(path_size); if (path) { snprintf(path, path_size, "%s%s", dir, array[0]); in = fopen(path, "r"): /* Slight differences to your invocation. */ free(path); } 
+2
source

All Articles