1

So i am trying to read from a text file and put it in a variable

in the text file there is

NAME= Bame
GAME= Fame

I've heard of strsep/strtok but i'm still having issues and with this code i get Segmentation Fault 11

    #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
char *token;
char *string;
char *tofree;
FILE *fp;
const char *file = "/tmp/test.txt"; 
fp = fopen(file, "r");
while(!feof(fp)) {
fgets(string, sizeof(string), fp);
token = strsep(&string, ",");
printf("%s", string);
}
fclose(fp);
exit(0);    
}
Exsanity
  • 33
  • 4
  • 3
    `char* string;` is _not_ a string. It is a pointer to a `char` that points "nowhere" since it is not initialized. You write into this uninitialized pointer thus invoking UB. Hence the crash. Fix by using character arrays: `char string[100];`. Also see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). So, replace your `feof` with your `fgets`. – Spikatrix Mar 31 '17 at 14:53
  • 1
    `fp = fopen(file, "r"); if (fp == NULL) { perror(Error opening file: "); return 1;}` – LPs Mar 31 '17 at 14:54
  • See also [Why is while( !feof(file) ) always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – John Bollinger Mar 31 '17 at 14:57

1 Answers1

1

The main problem is from this line:

fgets(string, sizeof(string), fp);

The second parameter should be 'Maximum number of characters to be copied into str'. You should have initialised string to something before calling this function. If you look at the example in the link I gave, changing string to a character array will help you more forward.

char string[100];
....
fgets(string, 100, fp);    

Previously you were passing sizeof(string), however since string was actually a pointer type, you were passing the size of a pointer in bytes (either 4 or 8 depending on platform). string was also an unallocated pointer, so fgets would have been potentially writing to a random memory address.

noggin182
  • 627
  • 4
  • 14