简体   繁体   English

在C中:从文件读取整数

[英]In C: Reading integers from a file

I have a function that basically read integers from a file: 我有一个基本上从文件读取整数的函数:

FILE *file;

file = fopen("filename.txt", "r");
fscanf(file, "%d", &(*pn));
fscanf(file, "%d", &(*pm));
fscanf(file, "%d", &(*pmax));

printf("*pm = %d\n", *pm);
printf("*pn = %d\n", *pn);
printf("*pmax = %d\n", *pmax);

First I tried with the following file: 首先,我尝试使用以下文件:

5 4 5 4

128 128

My output was correct, as I wanted: 我想要的输出是正确的:

*pm = 4
*pn = 5
*pmax = 128

But the real file is: 但是实际文件是:

P2 P2

5 4 5 4

128 128

I wanted my output to be as the one before, but then I got: 我希望输出与以前一样,但是后来我得到了:

*pm = 0
*pn = 0
*pmax = 0

What went wrong? 什么地方出了错?

The file starts 文件开始

P2

with a letter, not a digit. 用字母,而不是数字。 Thus the fscanf calls all fail to convert the input to an integer, consuming no input. 因此, fscanf调用都无法将输入转换为整数,不消耗任何输入。

You should always check the return value of the scanf family of functions to catch conversion failures due to malformed input or corrupted streams. 您应始终检查scanf系列函数的返回值,以捕获由于输入格式错误或流损坏而导致的转换失败。

You can skip the first line with, for example, 您可以使用以下方式跳过第一行:

fscanf(file, "%*[^\n]");

It's trying to read an int , but getting P . 它试图读取一个int ,但是得到P Since that can't convert to int , it's left in the stream, and the conversion fails. 由于无法将其转换为int ,因此将其保留在流中,并且转换失败。 The same happens for the second and third numbers. 第二个和第三个数字也一样。

Rereading your input, you probably want to do something like reading a string, then attempting to convert that to an int. 重新读取您的输入,您可能想要做一些事情,例如读取字符串,然后尝试将其转换为int。 You could read with %s , then convert with strtol . 您可以使用%s阅读,然后使用strtol进行转换。 If that doesn't convert, ignore it and try again. 如果那不能转换,请忽略它,然后重试。

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

char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && isspace(ch));//skip space chars
    ungetc(ch, fp);
    while(EOF!=(ch=fgetc(fp)) && !isspace(ch)){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

enum {false, true };

int readInt(FILE *fp, int *n){
    char *token, *endp;
    long wk;

    for(;;){
        token = inputString(fp, 16);//separated by space character
        if(!*token){//EOF
            free(token);
            return false;
        }
        wk = strtol(token, &endp, 0);
        if(*endp=='\0')break;//success read int
        free(token);
    }
    *n = (int)wk;
    free(token);
    return true;
}

int main(void){
    FILE *file;
    int n, m, max,i;

    n = m = max = 0;
    file = fopen("filename.txt", "r");
    readInt(file, &n);
    readInt(file, &m);
    readInt(file, &max);
/*
    printf("debug:");
    if(readInt(file, &i)==false){
        printf("false\n");
    }
*/
    fclose(file);

    printf("m = %d\n", m);
    printf("n = %d\n", n);
    printf("max = %d\n", max);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM