2014-06-13 76 views
1

我有一个文件,有超过6000行的错误数据。阅读直到行结尾

P000800 Engine Position System Performance 
P000900 Engine Position System Performance 
P001000 "A" Camshaft Position Actuator Circuit 
P001100 "A" Camshaft Position - Timing Over-Advanced or System Performance 
P001200 "A" Camshaft Position - Timing Over-Retarded 

第一个字符串总是在左边,然后是空格和描述。

对于我的生活,我似乎无法记住如何让它读取描述,直到 行尾。

我把到另一个文件看起来像这样的MySQL进口

P000800,Engine Position System Performance 
P000900,Engine Position System Performance 
P001000,"A" Camshaft Position Actuator Circuit 
P001100,"A" Camshaft Position - Timing Over-Advanced or System Performance 
P001200,"A" Camshaft Position - Timing Over-Retarded 

除非你知道一个更简单的方法,使之成为MySQL数据库兼容这一点。

while ((fgets(line, sizeof(line), fp_code) != NULL) && (line[0] != '\n')){ 
    sscanf(line,"%s %s",ercode, desc); 
} 

感谢 鲍勃

+0

在http://codereview.stackexchange.com/questions/31095/reading-unlimited-input-strings-in-c/31106#31106 – chux

+0

'如果(的sscanf(行的一些想法,“%s% [^ \ n]“,ercode,desc)== 2)GoodToGo();' – chux

回答

0

你怎么申报line:是它像char *linechar line[100]?这很重要,因为您获得其大小的方式是使用sizeof运算符。对于第一个,sizeof将给你一个指针的大小,而对于第二个,它会给你的实际大小是100.

此外,你检查的换行符应该是最后一个字符,line[strlen(line) - 1],而不是第一个字符line[0]

另一件事,你不能依靠fgets获取线中的所有字符,因为你受到sizeof(line)的限制。一种解决方案是迭代,直到获得换行符,然后将字符串作为整体处理。

+0

我声明它是char line [256]; – bpross

+0

chux&R Sahu这些工作很棒。他们不允许我投票给你的回复。 – bpross

0

实际实现我所看到的,这是不那么优雅,但工作,是使sscanf扫描这样的一定数量的%s的:

// scans up to 50 words in a line 
int Read_Words_From_String(char *StringLine, char **StringArray) 
{ 
    return(sscanf(StringLine, "%s%s..//which goes on to the count of 50..%s%s", 
        StringArray[0], // would contain ercode in your case 
        StringArray[1], 
        : // which goes on to the count of 50 
        StringArray[49])); 
} 

sscanf返回扫描,所以它的单词数可以用作循环计数器来将它们处理成另一种字符串格式。

+0

Why_Do_You_Write_Your_Subroutines_Like_This? –

+0

它是遗留代码的实际函数名称。 – Keugyeol

+0

Oh_Okay。 That_Makes_Sense_Now –

0

下面是一个适用于几乎与BUFSIZ一样长的线路的版本。

#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char** argv) 
{ 
    char token[10]; 
    char rest[BUFSIZ]; 

    FILE* in = fopen(argv[1], "r"); 
    if (in == NULL) 
    { 
     return EXIT_FAILURE; 
    } 

    // Explanation of the format: 
    // %9s  Read at most 9 characters into a string 
    // %[^\n] Read all characters until '\n' into a string 
    // %*c  Read a character but don't store it. Takes care of 
    //   getting rid of the `\n' from the input stream. 
    while (fscanf(in, "%9s %[^\n]%*c", token, rest) == 2) 
    { 
     printf("%s,%s\n", token, rest); 
    } 

    fclose(in); 
    return EXIT_SUCCESS; 
}