从文件中读取数据

发布于 2024-11-15 00:51:56 字数 436 浏览 0 评论 0原文

如何将文件中的数据读取到结构体中? 我有一个类似于

struct data
{
    char name[20];
    int age;
};

文件 student_info.txt 的结构,等等

   ravi 12 raghu 14 datta 13 sujay 10 rajesh 13

,还有许多其他年龄的名字。如何将其从文件读取到结构数据?

读取这个名字和年龄应该是一个循环,即第一次我将读取“ravi”和“12”,然后我应该将这些数据打包到结构中,并在结构设置后立即将结构传递给函数。它应该返回到文件并再次读取“raghu”和“14”,并用这些数据打包结构,这应该处于循环状态,直到我从文件中读取所有数据为止。

任何人都可以告诉我如何实现逻辑吗?

How to read the data from a file to a structure?
I have a structure like

struct data
{
    char name[20];
    int age;
};

In file student_info.txt I have

   ravi 12 raghu 14 datta 13 sujay 10 rajesh 13

and so on with many other names with ages. How can I read this from file to the structure data?

Reading this name and age should be a loop i.e for the first time I will read 'ravi' and '12', then I should pack this data in the structure and will pass the structure to a function as soon as the structure is set. It should come back to the file and read 'raghu' and '14' again pack the structure with this data, and this should be in a loop till I read all the data from the file

Can anyone please tell how to implement the logic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏九 2024-11-22 00:51:56

方法是:

  1. 创建结构体数组的实例、用于文件访问的文件指针和计数器变量
  2. 使用文件指针打开文件流 - 检查它是否已成功打开。如果 fopen() 失败,文件指针将指向 NULL
  3. 使用循环将数据读入结构体数组。 fscanf() 返回与其格式字符串成功“匹配”的数量 - 此处为 2(将其用于循环条件)
  4. 关闭文件

代码示例:

#include <stdio.h>

#define FILENAME "student_info.txt"
#define MAX_NO_RECORDS 50

struct data
{
char name[20];
int age;
};

int main(void)
{
    /* Declare an array of structs to hold information */
    struct data StudentInfo[MAX_NO_RECORDS];
    /* Declare a file pointer to access file */
    FILE *s_info;
    int student_no = 0; /* holds no. of student records loaded */

    /* open the file for reading */
    s_info = fopen(FILENAME, "r");
    /* Check if an error has occured - exit if so */
    if(s_info == NULL)
    {
        printf("File %s could not be found or opened - Exiting...\n", FILENAME);
        return -1;
    }

    printf("Loading data...\n");
    while(fscanf(s_info, "%19s %i", StudentInfo[student_no].name, &StudentInfo[student_no].age) == 2)
    {
        /* refer to records with index no. (0 to (1 - no. of records))
            individual members of structure can be accessed with . operator */
        printf("%i\t%-19s %3i\n", student_no, StudentInfo[student_no].name, StudentInfo[student_no].age);
        student_no++;
    }
    /* after the loop, student_no holds no of records */
    printf("Total no. of records = %i\n", student_no);
    /* Close the file stream after you've finished with it */
    fclose(s_info);

    return 0;
}

The approach is:

  1. Create an instance of an array of your struct, a file pointer for file access, and a counter variable
  2. Open the file stream using the file pointer - check that it has been successfully opened. The file pointer will point to NULL if fopen() has failed
  3. Read the data into the struct array using a loop. fscanf() returns the number of successful 'matches' with its format string - here it will be 2 (use this for the loop condition)
  4. Close the file

An example of the code:

#include <stdio.h>

#define FILENAME "student_info.txt"
#define MAX_NO_RECORDS 50

struct data
{
char name[20];
int age;
};

int main(void)
{
    /* Declare an array of structs to hold information */
    struct data StudentInfo[MAX_NO_RECORDS];
    /* Declare a file pointer to access file */
    FILE *s_info;
    int student_no = 0; /* holds no. of student records loaded */

    /* open the file for reading */
    s_info = fopen(FILENAME, "r");
    /* Check if an error has occured - exit if so */
    if(s_info == NULL)
    {
        printf("File %s could not be found or opened - Exiting...\n", FILENAME);
        return -1;
    }

    printf("Loading data...\n");
    while(fscanf(s_info, "%19s %i", StudentInfo[student_no].name, &StudentInfo[student_no].age) == 2)
    {
        /* refer to records with index no. (0 to (1 - no. of records))
            individual members of structure can be accessed with . operator */
        printf("%i\t%-19s %3i\n", student_no, StudentInfo[student_no].name, StudentInfo[student_no].age);
        student_no++;
    }
    /* after the loop, student_no holds no of records */
    printf("Total no. of records = %i\n", student_no);
    /* Close the file stream after you've finished with it */
    fclose(s_info);

    return 0;
}
星星的軌跡 2024-11-22 00:51:56

您只需从该文件中读取数据并根据某些条件拆分该字符串即可。由于您的文件格式不正确,您将很难解析数据。

在当前场景中,您的文件仅包含名字和数字,您可以通过检测字符串中的空格字符来轻松解析它。但如果您的任何名字包含空格,这可能会导致问题。

首先,用一些字符分隔每对单词,例如 : 或 ;或制表符或换行符。
然后在每个分隔的字符串之间用空格将其分割,然后读取字符数组中文件的所有内容,然后从该数组中尝试找到指示一条记录的特殊字符。
将每个记录分隔在不同的字符数组中,然后再次针对每个生成的数组,然后根据空格字符将其拆分并加载到结构中

这只是为了解释,原始实现可能有所不同,

Student std = {first string, second integer};

希望该文档能够解决您的问题 http://www.softwareprojects.com/resources//t-1636goto.html

You just need to read data from this file and split that string based on some criteria. as your file is not properly formatted it would be difficult for you to parse data.

In your current scenario your file contain only first name and a digit you can easily parse this by detecting a Space Character in your string. but this could lead a problem if any of your name contains a space.

First of all separate each pair of word by some character such as : or ; or a tab or line break.
then between each separated string split it by space and then read all content of file in a char array then from that array try to find that special character which indicates one record.
Separate each record in a different char array then for each generated array again and then split it based on space char and load in your struct

This is just for explanation, original implementation may be different,

Student std = {first string, second integer};

Hope that document solves your problem http://www.softwareprojects.com/resources//t-1636goto.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文