0

Help me with files in C

Why does this work? 1) #include <stdio.h> void main() { FILE *fptr=fopen("/storage/emulated/0/Cxxdroid/Fileoperations/myfile.txt","r"); char str1[20]; fgets(str1,20,fptr); printf("%s",str1); } But this doesn't? 2) #include <stdio.h> void main() { FILE *fptr=fopen("/storage/emulated/0/Cxxdroid/Fileoperations/myfile.txt","r"); char* str1; fgets(str1,20,fptr); printf("%s",str1); }

8th Jun 2021, 5:29 AM
Rishi
Rishi - avatar
2 odpowiedzi
+ 3
For the second snippet, you must initialize <str1> using either malloc() or calloc() before you can use it as buffer for reading data. And use free() afterwards, to release the allocated memory block once you are done using it. http://www.cplusplus.com/reference/cstdlib/malloc/ http://www.cplusplus.com/reference/cstdlib/calloc/ http://www.cplusplus.com/reference/cstdlib/free/
8th Jun 2021, 5:47 AM
Ipang
+ 1
Ipang oh yes yes now it works. Thank you so much✌️✌️✌️
8th Jun 2021, 6:17 AM
Rishi
Rishi - avatar