Does fscanf separate memory and put NUL bytes at the end of a line?

If I'm right, I’ll do something like:

char *line;

Then I have to allocate some memory and assign it to the line, is that right? If I am right, the question is:

In a line like

while (fscanf(fp,"%[^\n]", line) == 1) { ... } 

without assigning any memory to the string. I still get the correct rows and the correct row values ​​in such rows.

So, fscanfassigns this memory to me, and also puts '\0'? I did not see mention of these two things in the specification for fscanf.

+4
source share
5 answers

C POSIX, getline (3). ( ) , . . .

POSIX getline, fgets (3), , , . (, malloc) fgets ( realloc , fgets ). - :

 //// UNTESTED CODE
 size_t linsiz=64;
 char* linbuf= malloc(linsiz);
 if (!linbuf) { perror("malloc"); exit(EXIT_FAILURE); };
 memset(linbuf, 0, sizeof(linbuf));
 bool gotentireline= false;
 char* linptr= linbuf;
 do {
   if (!fgets(linptr, linbuf+linsiz-linptr-1, stdin))
     break;
   if (strchr(linptr, '\n')) 
     gotentireline= true;
   else {
     size_t newlinsiz= 3*linsiz/2+16;
     char* newlinbuf= malloc(newlinsiz);
     int oldlen= strlen(linbuf);
     if (!newlinbuf) { perror("malloc"); exit(EXIT_FAILURE); };
     memset (newlinbuf, 0, newlinsiz); // might be not needed
     strncpy(newlinbuf, linbuf, linsiz);
     free (linbuf);
     linbuf= newlinbuf;
     linsiz= newlinsiz;
     linptr= newlinbuf+oldlen;
    );
  } while(!gotentireline);
  /// here, use the linbuf, and free it later

(, char *line=NULL; ) malloc, calloc, realloc). , (gcc -Wall -Wextra -g). .

, , ( , ).

valgrind, , ..

+4

POSIX scanf() , m (a POSIX). :, fscanf , char **. (. man scanf) :

while(fscanf(fp,"%m[^\n]", &line) == 1) { ... }

newline "%m[^\n]%*c". , line-oriented fscanf. (, getline - .: Basile )

+7

. C:

:

char *p;
strcpy(p, "abc");

. ? ?

A: , . , p, , , -, - . . 11.35.

, .

+5

line , undefined.

, - .

PS: , fgets() . , fgets() .

+3

. undefined . , segfault , , , -. , , , , - .

+2

All Articles