繁体   English   中英

从 txt 文件 C 中读取 integer

[英]read integer from txt file C

我试图通过从文件中读取变量来初始化我的变量。 然而,我很难在不编写 50 多行代码的情况下做出有用的东西。 也许有人可以给我提示如何处理这个问题。

我的文本文件是这样的:它保证在“=”之后总是跟在一个整数(可能是一些空格)之后,但绝不是其他任何东西。

一=12

b= 4 c = 14

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

void getAB(int *a, int*){
FILE *file;
file = fopen("file.conf", "r");
// read a and b an their content from file.conf

fclose(file);
return;
}



int main(){
int a,b;
getAB(&a, &b);

printf("A = %i B = %i\n",a, b);
return 0;
}

我建议使用 fscanf(),

fscanf() function 用于从文件中读取格式化输入。 它的工作方式与 scanf() function 类似,但它不是从标准输入读取数据,而是从文件读取数据。

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strerror
#include <errno.h>  // errno
#include <err.h>    // errx


FILE *file_open(void);
void getAB(int *, int *);

FILE *fp = NULL;

int
main(void)
{
    int a, b;

    getAB(&a, &b);
    
    exit(EXIT_SUCCESS);
}

// open a file to read
FILE
*file_open(void)
{   
    extern FILE *fp;
    

    if ((fp = fopen("file.conf", "r")) == NULL)
        errx(EXIT_FAILURE, "%s", strerror(errno));

    return fp;
}


void
getAB(int *a, int *b)
{
    extern FILE *fp;

    fp = file_open();
    
    while (fscanf(fp, "%d %d", a, b) == 2)
        printf("A = %i, B = %i\n", *a, *b);
    
    fclose(fp);
}

fscanf是这项工作的正确工具:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

void getAB(int *a, int *b)
{
    FILE *file;
    file = fopen("file.conf", "r");
    fscanf(file, " a = %d ", a);
    fscanf(file, " b = %d ", b);
    fclose(file);
    return;
}

int main(void)
{
    int a, b;
    getAB(&a, &b);
    printf("A = %i B = %i\n",a, b);
    return 0;
}

暂无
暂无

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

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