How to overwrite a preallocated char array in C -


i initialize char array global variable in c program default file location/name as

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

later in program, if condition satisfied read file containing 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; // <---- wrong/unsafe?      }      return 0; } 

i should note assumed file fname contains 1 line 2 strings. show general framework of code. question, highlighted in code, wrong or unsafe try , reassign char file variable new string?

the size of newfile string differ it's original default size. default has predefined, since condition may not require new file read. if assignment wrong or unsafe, better approach?

you need declare file it's large enough hold newfile.

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

then when want update it, use:

strcpy(file, newfile); 

Comments