“
c,#include,#includeint main() {, FILE file = fopen("database.txt", "r");, if (file == NULL) {, perror("Error opening file");, return EXIT_FAILURE;, }, char line[256];, while (fgets(line, sizeof(line), file)) {, printf("%s", line);, }, fclose(file);, return EXIT_SUCCESS;,},
“使用 C 语言按行从文件读取数据库
在许多应用程序中,数据存储和检索是至关重要的功能,对于小型应用或嵌入式系统,使用文件作为简单的数据库是一种常见的做法,本文将详细介绍如何使用 C 语言按行从文件中读取数据,并解析这些数据以模拟数据库操作。
1. 文件格式
假设我们有一个文本文件database.txt
如下:
ID | Name | Age |
1 | Alice | 30 |
2 | Bob | 25 |
3 | Charlie | 35 |
每一行代表一个记录,字段之间用竖线|
分隔。
2. 数据结构定义
我们需要定义一个结构体来表示每条记录:
typedef struct { int id; char name[50]; int age; } Record;
3. 读取文件函数
编写一个函数来打开文件、按行读取内容,并解析每行的数据填充到结构体数组中:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_LENGTH 100 #define MAX_RECORDS 100 Record records[MAX_RECORDS]; int record_count = 0; void read_database(const char filename) { FILE file = fopen(filename, "r"); if (!file) { perror("Failed to open file"); exit(EXIT_FAILURE); } char line[MAX_LINE_LENGTH]; while (fgets(line, sizeof(line), file)) { // 跳过标题行 if (record_count == 0) { record_count++; continue; } Record rec; char token = strtok(line, "|"); rec.id = atoi(token); token = strtok(NULL, "|"); strncpy(rec.name, token, sizeof(rec.name) 1); rec.name[sizeof(rec.name) 1] = '