Hi.. How do I skip the first line of a text file. I am not using getline() so I think I cannot use ignore() function. Is there any other way to ignore first line ?

.................
FILE *in;
         char line[1000];
         char *token;
         in = fopen(argv[1],"rt+");
         if( in == NULL) exit(1);
 int i=0; 
 while(! feof(in)) {
         
         //in.ignore(1000, '\n');
//         std::in.ignore ( 1000, '\n' );               
         fgets(line, 1000, in);
.................................

Thanks

Dani AI

Generated

With C stdio, there is no ignore; you must consume bytes until the end of the first line. A simple, portable approach is to read and discard characters until you hit a newline or EOF. This handles both short and very long header lines and files that do not end with a newline.

int ch;
if (in) {
    while ((ch = fgetc(in)) != '\n' && ch != EOF) {
        /* discard */
    }
    /* now read the rest of the file as usual */
}

If you switch to C++ iostreams, you can skip the first line without storing it using istream::ignore with a large count:

#include <fstream>
#include <limits>

std::ifstream fin(argv[1]);
if (!fin) { /* handle error */ }
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* proceed to read remaining lines */

Both approaches avoid relying on buffer sizes and work even if the first line is longer than expected. After skipping, read subsequent lines with your normal loop, checking the read function’s return value to detect end-of-file or errors. See fgetc and std::istream::ignore for details and edge cases (e.g., what happens on EOF).

Recommended Answers

All 4 Replies

You can't just simply ignore it. You have to read it and then don't use it for anything.

You could try this:

FILE *in;
    char line[1000];
    char *token;
    in = fopen(argv[1],"rt+");
    if ( in == NULL) exit(1);
    int i=0;
    // Read the first line... move the file pointer to
    // point to the end of the first line. Note that the
    // definition for end-of-line is the '\n' character.
    fgets(line, 1000, in);
    while (! feof(in))
    {

        // in.ignore(1000, '\n');
        // std::in.ignore ( 1000, '\n' );
        fgets(line, 1000, in);
        cerr << line << endl;
    }

Hope this helped!

Edit: I mean the same thing as what Ancient Dragon said in his post... He answered as I was typing this...

You could try this:

fgets(line, 1000, in);
    while (! feof(in))
    {
        // ...
    }

Why it's bad to use feof() to control a loop

[edit]I think the "rt+" mode is a nonstandard extension meaning "r+" .

[edit]And it might be preferable to do

fgets(line, sizeof line, in);

instead of

fgets(line, 1000, in);

(Preferred by me at least. :P)

Thanks guys for all your help :)

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.