ThatsRightJack
ThatsRightJack

Reputation: 751

How to overwrite a preallocated char array in C

I initialize a char array as a global variable in my C program with a default file location/name as

char file[] = "/home/jack/files/data.txt";

Later in the program, if a condition is satisfied I read a file containing a new file name

int read_new_file(char *fname)
{
    FILE *inp;
    char buffer[255];
    char oldFile[127], newFile[127];

    inp = fopen(fname, "r");
    while ( fgets(buffer, 255, inp) != NULL )
    {
         sscanf(buffer, "%s %s",oldFile,newFile);

         file = newFile; // <---- Is this wrong/unsafe?

    }

    return 0;
}

I should note that it is assumed file fname only contains one line with 2 strings. This was just to show the general framework of the code. My question, as highlighted in the code, is it wrong or unsafe to simply try and reassign the char file variable with the new string?

The size of the newFile string will likely differ from it's original default size. The default has to be predefined, since the condition may not require a new file to be read. If the assignment is wrong or unsafe, what is a better approach?

Upvotes: 1

Views: 1859

Answers (2)

R Sahu
R Sahu

Reputation: 206697

file = newFile; // <---- Is this wrong/unsafe?

It is wrong since file is an array. The compiler won't let you do that. Whether it is safe or not is not relevant since you can't do it.

Use strcpy instead.

strcpy(file, newFile);

Upvotes: 1

Barmar
Barmar

Reputation: 781974

You need to declare file so it's large enough to hold newFile.

char file[127] = "/home/jack/files/data.txt";

Then when you want to update it, you use:

strcpy(file, newFile);

Upvotes: 3

Related Questions