hello
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!");}
        
         while(!feof(source)){  
              x = fgets(line,MAXLINE,source);
              printf("%s\n",x);}
        
       fclose(source);

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

because:

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:
http://cplusplus.com/reference/clibrary/cstdio/fgets/


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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.