I didn't find the answer on internet if there is please link it...
#include <stdio.h>
int main(){
FILE*fp;
char arr[4];
printf("Opening...\n");
fp=fopen("slide.txt", "r");
printf("Opened\n");
if(fp==NULL){
printf("No such file\n");
return 1;
}
fscanf(fp, "%s", arr);
printf("Printing...\n");
printf("%s\n", arr);
printf("Printed\n");
printf("Closing...\n");
fclose(fp);
printf("Closed\n");
return 0;
}
Content of the file:
ciao
Output that I have:
Opening...
Opened
Printing...
ciao
Printed
Closing...
Segmentation fault (core dumped)
CodePudding user response:
Declare the character array at least like
char arr[5];
and use
fscanf(fp, "%4s", arr);
That is you need to reserve a space in the array for the terminating zero character '\0'
for the read string.