C在不同情况下无法找到从文件读取数据的工作算法

时间:2021-10-15 16:22:45

I have actually a small problem with file i/o and finding the right algorithm to read the data correctly. The problem is, that the "header" could look a little bit different from each file.

我实际上有一个文件i / o的小问题,并找到正确的算法来正确读取数据。问题是,“标题”看起来与每个文件有点不同。

For example:

File 1.
500 500
100
Binary

File 2.
500

d500
100
Binary

File 3.
   500
500

100
Binary

File 4.
500
500       100
Binary

...

I’m interested to get the 3 numeric values. I tried it with fgets and scanf and also with fscanf... and so one. But I find at every try a way, where I’m not able to get the values.

我有兴趣得到3个数值。我尝试了fgets和scanf以及fscanf ......等等。但我发现每一次尝试的方式,我都无法获得价值。

Dose someone have some ideas, who I could get the values in every case?

有人有一些想法,我可以在每种情况下获得价值观吗?

Edit

/* Jump over the identification and comment strings. */
        fseek(in, 3, SEEK_SET);
        do
        {
            fgets(line, PREAMBLE, in);
        } while(strncmp(line, "#", 1) == 0);

        /* Save the information in the structer. */
        sscanf(line, "%u %u", &imginf.width, &imginf.height);
        fgets(line, PREAMBLE, in);
        sscanf(line, "%u", &imginf.depth);
        return imginf;

This works for example:

这适用于例如:

File
500 500
100
Binary

Solution

Her is the interesting part of the code. Now I think I get every value. Maybe the code looks a little bit smelly, I haven not made sure that the code is clean.

她是代码中有趣的部分。现在我想我得到了每一个价值。也许代码看起来有点臭,我还没确定代码是干净的。

  while (a[2] == 0 ){
        fgets(line, 255, in);
        i = 0;
        while (line[i] != '\0') {
            if ((line[i] < '0') || (line[i] > '9')) {
                i++;
            }
            else {
                while ((line[i] >= '0') && (line[i] <= '9')) {
                    buffer[j] = line[i];
                    j++;
                    i++;   
                }
                j = 0;
                a[k] = atoi(buffer);
                printf("%d\n", a[k]);
                strcpy(buffer, "");  
                k++;
            }
        }
    }

Greetz

1 个解决方案

#1


4  

Read character-by-character and parse the input yourself.

逐个字符地阅读并自己解析输入。

Something like

do 3 times {
    ignore anything not a digit
    read number digit-by-digit
}
// input is now pointing to the 2nd non-digit
// just after the last digit of the 3rd number
// the 1st non-digit should be saved in the variable you used in the loop

#1


4  

Read character-by-character and parse the input yourself.

逐个字符地阅读并自己解析输入。

Something like

do 3 times {
    ignore anything not a digit
    read number digit-by-digit
}
// input is now pointing to the 2nd non-digit
// just after the last digit of the 3rd number
// the 1st non-digit should be saved in the variable you used in the loop