简体   繁体   English

如何从文本文件中读取数据并将其存储在 C 语言的变量中?

[英]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.我正在尝试读取 C 中的文本文件。 The name of the file is test.txt and has the following kind of format.文件的名称是test.txt ,格式如下。

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.我编写了这个 C 代码来读取 Nx、Ny 和 T 的值,它们分别为 2、4 和 10。

#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.但是得到了这个 output。 This output is wrong as the values of Nx, Ny, and T are not matching with the data given above.这个 output 是错误的,因为 Nx、Ny 和 T 的值与上面给出的数据不匹配。

代码输出

Please help me to solve this problem.请帮我解决这个问题。

junk1 and junk2 should be arrays of char to be able to store strings. junk1junk2应该是 char 的 arrays 才能存储字符串。

But since it is junk you could simply not store it anywhere by using * in the fscanf conversion specifiers:但是由于它是垃圾文件,因此您不能通过在fscanf转换说明符中使用*将其存储在任何地方:

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

fscanf documentation: https://en.cppreference.com/w/c/io/fscanf fscanf文档: 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文件"test.txt"存在于当前目录,可以读取
  • it contains at least 3 settings, in the order Nx , Ny , T .它包含至少 3 个设置,顺序为NxNyT

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.将带有%s的字符串读入单个字符变量junk1将导致未定义的行为,对于junk2 ,因为fscanf()将尝试存储字符串中的所有字符以及目标地址处的 null 终止符,从而覆盖其他可能造成灾难性后果的数据.
  • main has a return type int . main有一个返回类型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;
}

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

相关问题 C 语言 - 从文本文件中读取特定数据 - C language - Read specific data from text file 如何使用C语言中的数组方法从文本文件中读取数据并对特定列进行升序排序? - How to read data from text file and sort a specific column in ascending order using the array method in C language? 如何从文本文件中读取值并将其存储在C中的不同变量类型中 - How to read values from a text file and store them in different variable types in C 如何在 c 语言中使用 fscanf 从文件中读取数据 - How to read data from file with fscanf in c-language 如何从 C 中的文本文件中读取数据 - How to read data from a text file in C 如何从文本文件中读取数据并将其存储在我的 C 程序中以在函数中使用? - How do I read data from a text file and store it in my C program to be used in functions? 如何从文本文件读取二进制数据并将其存储在C中的2D数组中 - How do I read binary data from a text file and store it in a 2D array in C 从文件中读取并将其存储在变量c中 - read from a file and store it in a variable c 如何从文本文件读取并存储在c矩阵中 - how to read from text file and store in matrix in c 如何从.txt文件中读取文本,然后将其存储在记录(数据结构)中? - How to read text from a .txt file and then store it in a record (data structure)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM