Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C txt文件中的只读值_C_Arrays_Parsing_Variables - Fatal编程技术网

C txt文件中的只读值

C txt文件中的只读值,c,arrays,parsing,variables,C,Arrays,Parsing,Variables,我正在尝试从txt文件中读取变量。 txt文件类似于: john 10 mark 230 peter 1 我想在数组中传输并保存这些值,例如数组[0]=10、数组[1]=230等,而不考虑名称。我在下面粘贴了我的代码,我想知道如何使用下面的代码进行编辑 int conf[4], i = 0, c; FILE *file_conf; file_conf = fopen("conf.txt", "r"); if(file_conf == NULL){ fprintf(stderr, "Er

我正在尝试从txt文件中读取变量。 txt文件类似于:

john 10
mark 230
peter 1
我想在数组中传输并保存这些值,例如数组[0]=10、数组[1]=230等,而不考虑名称。我在下面粘贴了我的代码,我想知道如何使用下面的代码进行编辑

int conf[4], i = 0, c;
FILE *file_conf;
file_conf = fopen("conf.txt", "r");

if(file_conf == NULL){
   fprintf(stderr, "Error\n");
   exit(EXIT_FAILURE);
} else {
    while((c = fgetc(file_conf)) != EOF) { 
        fscanf(file_conf, "%d", &conf[i]);
        printf("%d\n", conf[i]);
        i++; 
    }
}   

您根本不应该使用
fgetc()
——它只包含一个字符。相反,将名称格式添加到您的
fscanf()
,如下所示:

char name[100];
fscanf(file_conf, "%s %d", name, &conf[i]);
您可以在
scanf()
族转换说明符前面加上
*
前缀以禁止赋值。请注意,在发布的代码中,未能检查从
fscanf()
返回的值可能会导致输入格式错误。此外,当数组索引
i
过大时,输入循环应该退出,以避免缓冲区溢出。当
i
太大或遇到格式错误的输入时,以下代码退出循环:

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

int main(void)
{
    int conf[4], i = 0;
    FILE *file_conf;
    file_conf = fopen("conf.txt", "r");

    if(file_conf == NULL){
        fprintf(stderr, "Error\n");
        exit(EXIT_FAILURE);
    } else {
        while(i < 4 && fscanf(file_conf, "%*s%d", &conf[i]) == 1) {
            printf("%d\n", conf[i]);
            i++; 
        }
    }

    fclose(file_conf);

    return 0;
}