i have a problem in reading lines from a file.i use the following code and the printf returns null.

char* x;
       MAXLINE =100;
       char line[MAXLINE];
       FILE *source; 

       source = fopen("data.txt","r");
        if (source == NULL){
            printf("ERROR!!!file not found!");}
              x = fgets(line,MAXLINE,source);

In your " printf " statements,
You should use: " puts " instead.


char * fgets ( char * str, int num, FILE * stream );

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.

A null character is automatically appended in str after the characters read to signal the end of the C string.

refer to:

Hope it helped, bye.

ok thanks works ok now for lines but how can i get separate words and store each one into a char*???

If you want to read words instead of lines call fscanf() instead of fgets(). But with fscanf() the program can not distinguish end-of-line. If it needs to know about EOL and also read words then you will want to call fgets() and parse the string into words. strtok() can be useful for that, assuming you don't mind that strtok() will put NULL bytes in the string where the tokens (spaces) appear.

>>and the printf returns null
The return value of printf() is normally ignored. If printf() fails it will return a negative value, not null.

Edited 5 Years Ago by Ancient Dragon: n/a

This article has been dead for over six months. Start a new discussion instead.