简体   繁体   中英

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. 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

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(),

The fscanf() function is used to read formatted input from the file. It works just like scanf() function but instead of reading data from the standard input it reads the data from the file.

#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:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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