0

I need to store in a text file two integers and then the lines of a text. i've successfully done it by writing each int in a line and each line of the text in a new line too. In order to read it, however, I've found some troubles. I'm doing this:

FILE *f = fopen(arquivo, "r");
char *lna = NULL;
fscanf(f, "%d\n%d\n", &maxCol, &maxLin);
//↑This reads the two ints, works fine in step-by-step
for (;;) {
    fscanf(f, "%s\n", &lna);
    //↑This sets lna to NULL always, even if there are more lines
    if (lna != NULL)
        lna[strlen(lna) - 1] = '\0';
    if (feof(f))
        break;
    inserirApos(lista, lna, &atual);
}
fclose(f);

I've tryied a few different ways, but they never worked. I understand I can read everthing like strings, with gets or something, but I think that has a problem if the string contains spaces. I wanted to know if the way I'm doing is the best, and what's wrong with it. I've found one of these methods (that didn't work either) that you have to pass the maximum length of each line. I know this information if necessary, it's the maxCol I read before.

Luan Nico
  • 5,376
  • 2
  • 30
  • 60

3 Answers3

2
fscanf(f, "%s\n", &lna);

Is the wrong argument type. The %s format expects a char* as argument, but you gave it a char**. And you have not allocated memory to that pointer. fscanf expects a char* pointing to a large enough memory area.

char *lna = malloc(whatever_you_need);
...
    fscanf("%s ", lna);

(no difference between the '\n' and ' ' in the fscanf format. both consume the entire whitespace following the string of non-whitespace characters scanned int lna.)

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

You need to allocate the space for lna first.

char *lna = malloc(MAX_SIZE);//MAX_SIZE is the maximum size the string can be + 1 

The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.

Burkhard
  • 14,596
  • 22
  • 87
  • 108
  • Please [don't cast the return value of `malloc()`, in C](http://stackoverflow.com/a/605858/28169). – unwind Nov 19 '12 at 14:49
  • Thanks unwind. Didn't know that. When I started programming in C, it was still compulsory to cast... and now I mostly use C++ where it is also compulsory. – Burkhard Nov 19 '12 at 16:01
1

You seem to be expecting fscanf() to dynamically allocate strings for you; that's not at all how it works. This is undefined behavior.

unwind
  • 391,730
  • 64
  • 469
  • 606