ThatsRightJack ThatsRightJack - 3 months ago 11
C Question

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?

Answer

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);
Comments