Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a relative path to fopen()

Tags:

c

linux

file-io

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);
}
like image 204
Dino55 Avatar asked Feb 02 '12 22:02

Dino55


2 Answers

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);
}
like image 52
Sergey Kalinichenko Avatar answered Sep 20 '22 08:09

Sergey Kalinichenko


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);
}
like image 31
hmjd Avatar answered Sep 18 '22 08:09

hmjd