abhinavkulkarni
abhinavkulkarni

Reputation: 2389

Trouble creating a new file

I have a simple line in my C++ code to create a new file:

string fileName = "test";

// Create a file named "test"
rc = pf->CreateFile(fileName.c_str());

Inside CreateFile function (which takes const char *fileName as an argument, I have following snippet of code;

// Create the file in current working directory
char *path = NULL;
path = getcwd(path, 0);
path = strcat(path, "/");
path = strcat(path, fileName);
FILE *fHandle = fopen(path, "wb");

The string path contains full absolute path of the file to be created. The file name is test. However when I run the code, the file is indeed created, however its name contains unprintable characters (code was run between following two commands):

enter image description here

Please suggest what could be wrong.

Upvotes: 0

Views: 87

Answers (2)

hmjd
hmjd

Reputation: 121961

From man getcwd:

As an extension to the POSIX.1-2001 standard, Linux (libc4, libc5, glibc) getcwd() allocates the buffer dynamically using malloc(3) if buf is NULL. In this case, the allocated buffer has the length size unless size is zero, when buf is allocated as big as necessary. The caller should free(3) the returned buffer.

This means there is no extra space left in path to be appending to and results in overwriting the bounds of the array that path points to, causing undefined behaviour and is the probable cause of the unprintable characters.

To construct a buffer capable of holding the path you need to determine the full size, malloc() and build it:

char *path;
path = getcwd(path, 0);
if (path)
{
    /* The '+2' is for null terminator and the '/'. */
    const size_t size = strlen(path) + strlen(fileName) + 2;
    char* fullPath = malloc(size);
    if (fullPath)
    {
        sprintf(fullPath, "%s/%s", path, fileName);
        /* fopen() ... */
        free(fullPath);
    }
    free(path);
}

Upvotes: 2

Sdra
Sdra

Reputation: 2347

Your path variable probably doesn't end by \0.

Upvotes: 1

Related Questions