Search code examples
cfilelinefopenskip

Reading Text file in C, skip first line


I have a big problem with my program. I would like to skip reading from 1st line and then start reading from others. I wasted so much time on searching it in the Internet.

This is my txt file.

LP bfdhfgd ffhf  fhfhf hgf hgf hgf ffryt f uu  
1 2015-01-17 20:08:07.994 53.299427 15.906657 78.2 0
2 2015-01-17 20:09:13.042 53.299828 15.907082 73.3 11.2375183105
3 2015-01-17 20:09:22.037 53.300032 15.90741 71.2 12.2293367386
4 2015-01-17 20:09:29.035 53.300175 15.907675 71.5 10.8933238983
5 2015-01-17 20:09:38.003 53.30025 15.907783 71.4 12.3585834503
6 2015-01-17 20:09:49.999 53.300768 15.908423 72.4 14.1556844711
7 2015-01-17 20:09:58.999 53.300998 15.908652 73.7 11.2634601593
8 2015-01-17 20:10:06.998 53.301178 15.908855 72.6 10.8233728409
9 2015-01-17 20:10:15.999 53.301258 15.908952 72.3 10.3842124939
10 2015-01-17 20:10:22.999 53.301332 15.90957 71.5 10.7830705643

 
   void OK(char * name)
{
	GPS nr1; //my structure
	FILE *file;
	file = fopen(name, "r+t");

	if (file!=NULL)
	{
		cout << endl;
	    while (!feof(file)) 
        {
            fscanf(plik, "%d %s %d:%d:%f %f %f %f %f", &nr1.LP, &nr1.Date, &nr1.hour, &nr1.min, &nr1.sek, &nr1.dl, &nr1.sz,                 &nr1.high, &nr1.speed);
		    base.push_back(nr1);

		    cout << nr1.LP << " " << nr1.Date << " " << nr1.hour << ":" << nr1.min << ":" << nr1.sek << " " << nr1.dl << " " <<             nr1.sz<< " " << nr1.high << " " << nr1.speed <<endl;	
        }
	}
	else
	{
		cout << endl << "ERROR!";
		exit(-1);
	}

	fclose(file);

}


Solution

  • First off, your code is a little strange because you are mixing C++ Output with C input. You may want to fix that later.

    The way to get the behavior you want is to use fgets to read lines (and skip the first line), and then use sscanf to pull out the values.

    #include <stdio.h>
    
    
    void OK(char * name)
    {
        GPS nr1; //my structure
        FILE *file;
        file = fopen(name, "r");
    
        char buffer[1024];
        memset(buffer, 0, 1024);
    
        if (file!=NULL)
        {
            cout << endl;
            // skip first line
            fgets(buffer, 1024, file);
            while (!feof(file)) 
            {
                // Read a line and parse it.
                fgets(buffer, 1024, file);
                sscanf(buffer, "%d %s %d:%d:%f %f %f %f %f", &nr1.LP, &nr1.Date, &nr1.hour, &nr1.min, &nr1.sek, &nr1.dl, &nr1.sz, &nr1.high, &nr1.speed);
                cout << nr1.LP << " " << nr1.Date << " " << nr1.hour << ":" << nr1.min << ":" << nr1.sek << " " << nr1.dl << " " << nr1.sz<< " " << nr1.high << " " << nr1.speed <<endl;    
            }
        }
        else
        {
            cout << endl << "ERROR!";
            exit(-1);
        }
    
        fclose(file);
    
    }