簡體   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