-2

supposing i have a text file with this content :

this is the first line . 
this is the second line . 
this is the third line .

my point is to get every line in a separate string variable .

i tried something like this

   do { fgets(ch,1000,f);printf("%s \n",ch); } while(strlen(ch)!=0); 

whith "f" is a pointer to my file and ch my string variable .

Barmar
  • 741,623
  • 53
  • 500
  • 612
gaston_n
  • 11
  • 1
  • i'm trying to take each line and applicate other function on it 'separately' not displaying the whole content of the text file on console . – gaston_n Jan 04 '17 at 19:22
  • Use malloc or realloc. – BLUEPIXY Jan 04 '17 at 19:28
  • 1
    Use an array of `char*` pointers. Read each line into an array, use `malloc()` to allocate a string to hold the contents, copy the string, and put the pointer in the array. – Barmar Jan 04 '17 at 19:42
  • 1
    Your own attempt ought to work (for lines less than 999 characters), but change the test to check the return result of `fgets` itself. – Jongware Jan 04 '17 at 19:49

1 Answers1

1

If you want to use fgets(), you can try something like that:

char ch[999];   
FILE * f;
f = fopen( "test.txt" , "r");
if (f) 
{
    while(fgets(ch, sizeof(ch), f) != NULL)
    {
        printf("%s", ch);
    }
    fclose(f);
}

Then you can use the variable ch as you want.

Meuledor
  • 19
  • 4
  • 2
    You should include a note about how [a null character in the input stream can lead to unexpected results](http://stackoverflow.com/q/16323185/2615940) when using fgets(). – skrrgwasme Jan 04 '17 at 19:52
  • @skrrgwasme: you should note that `fgets` is to be used on text files, and "null bytes do not belong in **text** files. fgets() was designed to work with text files: using fgets() with files of binary data is not recommended. – pmg" (from a [comment](http://stackoverflow.com/questions/16323185/why-is-the-fgets-function-deprecated#comment23375681_16323215) in there). – Jongware Jan 05 '17 at 12:33