My file looks like:
123456789
My code gives me segmentation fault:
#include <stdio.h>
int main(){
FILE *f;
char ch[5];
f = open("a.txt", "r");
fgets( ch, 4, f);
ch[4] = NULL;
printf("%s", ch); //Fixed
return 0;
}
I am an absolute beginner. What am I doing wrong. My aim is to read first 4 characters of the file using fgets.
You’ll want to do
For the
%format, the argument is a pointer to characters; by passing a single character by value, you’re tellingprintfto interpret that character’s ASCII value as a pointer, and that’s going to blow up on you; i.e., if the character is a1, which is ASCII 49, then it’s going to look at byte 49 in memory for a string — and looking down there is generally verboten.But secondly, I see you’re calling
open()instead offopen(). You must usefopen()or you won’t get aFILE*as you’re expecting.Both of these individually would likely cause a segfault — you’ll need to fix them both.