简体   繁体   中英

How to read data from a text file and store it in a variable in C language?

I am trying to read a text file in C. The name of the file is test.txt and has the following kind of format.

Nx = 2
Ny = 4
T  = 10

I have written this C code to read the values of Nx, Ny, and T which is 2, 4, and 10 respectively.

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

void main()
{
    double Data[3];    // I'm interested in this information
    char junk1, junk2; // junk variables to avoid first two characters

    FILE * file = fopen("test.txt", "r"); // open file

    for(int i = 0; i < 3; i++) // each loop will read new line of file; i<3 for 3 lines in file
    {
        fscanf(file, "%s %s %lf\n", &junk1, &junk2, &Data[i]); //store info in Data array
        printf("%f\n", Data[i]); // print Data, just to check
    }
    fclose(file);

    int Nx; // store data in respective variables
    int Ny;
    double T;

    Nx = Data[0];
    Ny = Data[1];
    T  = Data[2];

    printf("Value of Nx is %d\n", Nx); // Print values to check
    printf("Value of Ny is %d\n", Ny);
    printf("Value of T is %f\n", T);
}

But got this as an output. This output is wrong as the values of Nx, Ny, and T are not matching with the data given above.

代码输出

Please help me to solve this problem.

junk1 and junk2 should be arrays of char to be able to store strings.

But since it is junk you could simply not store it anywhere by using * in the fscanf conversion specifiers:

fscanf(file, "%*s %*s %lf\n", &Data[i]);

fscanf documentation: https://en.cppreference.com/w/c/io/fscanf

Your program makes strong assumptions about the input file:

  • the file "test.txt" exists in the current directory and can be read
  • it contains at least 3 settings, in the order Nx , Ny , T .

It has problems too:

  • reading a string with %s into a single character variable junk1 will cause undefined behavior, same for junk2 , because fscanf() will attempt to store all characters from the string plus a null terminator at the destination address, overwriting other data with potentially catastrophic consequences.
  • main has a return type int .

Here is a more generic approach:

#include <stdio.h>
#include <string.h>

int main() {
    int Nx = 0, Ny = 0;
    double T = 0;
    int has_Nx = 0, has_Ny = 0, has_T = 0;
    char buf[80];
    FILE *file;

    if ((file = fopen("test.txt", "r")) == NULL) {
        fprintf(stderr, "cannot open test.txt\n");
        return 1;
    }

    while (fgets(buf, sizeof buf, file)) {
        if (buf[strspn(buf, " ")] == '\n')  /* accept blank lines */
            continue;

        if (sscanf(buf, " Nx = %d", &Nx) == 1)
            has_Nx = 1;
        else
        if (sscanf(buf, " Ny = %d", &Ny) == 1)
            has_Ny = 1;
        else
        if (sscanf(buf, " T = %lf", &T) == 1)
            has_T = 1;
        else
            fprintf(stderr, "invalid line: %s", buf);
    }
    fclose(file);

    // Print values to check
    if (has_Nx)
        printf("Value of Nx is %d\n", Nx);
    if (has_Ny)
        printf("Value of Ny is %d\n", Ny);
    if (has_T)
        printf("Value of T is %g\n", T);
    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