I have been working on a small exercise for my CIS class and am very confused by the methods C uses to read from a file. All that I really need to do is read through a file line by line and use the information gathered from each line to do a few manipulations. I tried using the getline method and others with no luck. My code is currently as follows:
int main(char *argc, char* argv[]){ const char *filename = argv[0]; FILE *file = fopen(filename, "r"); char *line = NULL; while(!feof(file)){ sscanf(line, filename, "%s"); printf("%s\n", line); } return 1; }
Right now I am getting a seg fault with the sscanf method and I am not sure why. I am a total C noob and just wondering if there was some big picture thing that I was missing. Thanks
Use the fscanf Function to Read File Line by Line in C The fscanf function is part of the C standard library formatted input utilities. Multiple functions are provided for different input sources like scanf to read from stdin , sscanf to read from the character string, and fscanf to read from the FILE pointer stream.
Reading a file line by line is a trivial problem in many programming languages, but not in C. The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.
Use the fgetc() function to read from a text file, a character at a time. Use the fgets() function to read from a text file, line by line.
So many problems in so few lines. I probably forget some:
So
#include <stdio.h> int main(int argc, char* argv[]) { char const* const fileName = argv[1]; /* should check that argc > 1 */ FILE* file = fopen(fileName, "r"); /* should check the result */ char line[256]; while (fgets(line, sizeof(line), file)) { /* note that fgets don't strip the terminating \n, checking its presence would allow to handle lines longer that sizeof(line) */ printf("%s", line); } /* may check feof here to make a difference between eof and io failure -- network timeout for instance */ fclose(file); return 0; }
To read a line from a file, you should use the fgets
function: It reads a string from the specified file up to either a newline character or EOF
.
The use of sscanf
in your code would not work at all, as you use filename
as your format string for reading from line
into a constant string literal %s
.
The reason for SEGV is that you write into the non-allocated memory pointed to by line
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With