简体   繁体   English

从 txt 文件 C 中读取 integer

[英]read integer from txt file C

I tried to initialize my variables with reading them out from a file.我试图通过从文件中读取变量来初始化我的变量。 However i struggle really hard to make something usefull without writing 50+ lines of Code.然而,我很难在不编写 50 多行代码的情况下做出有用的东西。 Maybe somebody can give me a hint how to deal with this.也许有人可以给我提示如何处理这个问题。

my text file ist like: Its guaranteed that after '=' always follows an integer(maybe some whitespace) but never smth else.我的文本文件是这样的:它保证在“=”之后总是跟在一个整数(可能是一些空格)之后,但绝不是其他任何东西。

a=12一=12

b= 4 c = 14 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;
}

I suggest using fscanf(),我建议使用 fscanf(),

The fscanf() function is used to read formatted input from the file. fscanf() function 用于从文件中读取格式化输入。 It works just like scanf() function but instead of reading data from the standard input it reads the data from the file.它的工作方式与 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 is the right tools for this job: 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