在C中读取文本文件,跳过第一行

Reading Text file in C, skip first line

我的程序有一个大问题。我想跳过第一行的阅读,然后开始阅读其他人的内容。我浪费了很多时间在互联网上搜索它。

这是我的 txt 文件。

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);

}

首先,您的代码有点奇怪,因为您混合了 C++ 输出和 C 输入。您可能想稍后修复它。

获得所需行为的方法是使用 fgets to read lines (and skip the first line), and then use sscanf 提取值。

#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);

}