Opening file from variable(C) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Opening file from variable(C)

https://code.sololearn.com/c2kD6uHq15kU/#c I have to open 26 files based on the input of the first file: the first file is series of 3 letters strings like ABC DEF etc. i have to open the files ABC.txt, DEF.txt... and im trying to do it with sprintf but it gives me an output i dont understand.

3rd Jul 2020, 5:33 PM
Guido Parlatore
Guido Parlatore - avatar
5 Answers
+ 3
There are several problems: * The char pointers are uninitialized. * The call to fgets would return only 2 bytes, not 3. * Files are not getting closed Solutions: The char pointers need to be char arrays so that there is memory available to store the strings. char*xyz; //should be: char xyz[4]; char*ilfile; //should be: char ilfile[8]; In the call to fgets() the second argument (parameter n) should be changed from 3 to 4 in order to read 3 bytes. Calling fgets() reads n-1 bytes from the file and then it always adds a null as the nth byte. Remember to close each file that you open. You should have fclose(aprixyz); within the while loop.
5th Jul 2020, 10:16 AM
Brian
Brian - avatar
+ 2
fopen does not work on sololearn. The playground is a remote server and cannot find the files on your computer. fgets does not work because is empty sommario
3rd Jul 2020, 8:32 PM
sneeze
sneeze - avatar
+ 1
I'm working on my computer, i just posted the code here to show it
3rd Jul 2020, 8:34 PM
Guido Parlatore
Guido Parlatore - avatar
+ 1
And sommario is the txt file that i described in the description
3rd Jul 2020, 8:35 PM
Guido Parlatore
Guido Parlatore - avatar
+ 1
Ok. Was not aware of that
3rd Jul 2020, 8:35 PM
sneeze
sneeze - avatar