Chris Loonam
Chris Loonam

Reputation: 5745

C reading past newline

When I type, for example, test \n test and try to use this code to write it

FILE *f = fopen(file, "w+");
fflush(f);
if (f==NULL) {
    //perror(f);
    return 0;
}
else{
    int i = fprintf(f, "%s", text);
    if (i>0) {
        fclose(f);

        return  1;
    }
    else{
        fclose(f);

        return 0;
    }
}

and then read it using this

FILE *f = fopen(file, "r");
static char c[100000];
const char *d;
if (f!=NULL) {
    if (fgets(c, 100000, f) !=NULL){
        d = c;
    }
    else{
        d = "No text";
    }
}
else{
    /*
     char *ff = f;
     perror(ff);
     */
    d = "File not found";
}
fclose(f);

return d;

it will only read and write test, not test, new line, test. Why won't this work?

Upvotes: 0

Views: 1645

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753860

The fgets() function reads up to the first newline it encounters, or stops when it runs out of space to store the result, or when it gets EOF (so there is no more data to read).

A subsequent call to fgets() will collect the information after the first newline.

If you want to read it all at once, consider fread(). OTOH, there are issues you'll have to resolve there, too (notably: (1) you may ask for up to 1000 bytes, but only get back 20, so your code will have to handle short reads correctly; and (2) fread() will not null terminate the input string for you, unlike fgets() etc).

When it comes to writing, fwrite() would be the logical complement to fread(), but you can perfectly well continue using fprintf() and friends, or fputs(), or putc(), or any of the other standard I/O writing functions. There's no formal constraint on 'if you write with these functions, you must read with these other functions'. It depends on the nature of what you're writing and reading, but you are often at liberty to switch as seems most convenient.

Upvotes: 5

Cristiano Sousa
Cristiano Sousa

Reputation: 932

http://www.cplusplus.com/reference/cstdio/fgets/

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 the end-of-file is reached, whichever happens first.

Upvotes: 3

Related Questions