I am trying to pass a relative path to fopen(), but it can't seem to find the file. I need this to work on Linux. The filenames (ex: t1.txt) are saved in an array. So all I need is the "front part" of a relative path.
Here's 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);
}
First, you need to add some space to path
in order to fit the content of array[0]
in strcat
, otherwise you'll be writing past the allocated area.
Second, you are not passing path
to fopen
, because you enclosed "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);
}
path
is only large enough to contain the characters it has been initialised with. The size of path
must be increased. Allocate memory for path
based on the filename being appended:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With