You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用全局变量的情况下将文件信息存入C语言结构体

问题描述

我有一个按类型、名称、正向连接(connection+)、反向连接(connection-)、数值顺序定义的电路。需要编写main函数外的函数,不使用全局变量,将文件中的电路信息存入结构体。目前只能通过全局变量实现该功能,求解决方案。

原代码
#define _CRT_SECURE_NO_WARNINGS

#include "fileio.h"

#include <string.h>

typedef struct {      
    char tipo, NoM, Nom;    
    char nome[20];    
    float valor;    
}organ;
    
organ circuito[7];  

int leitura(organ *circuito) {        
    FILE* fd;    
    char titulo[25];
    int i = 0;

    printf("Nome do Ficheiro: ");
    scanf("%s", titulo); //leitura do titulo dado pelo utilizador

    fd = fopen(titulo, "r");

    if (fd != NULL) { 
        while (fgetc(fd) != '\n');    
        i = 0;

        while (
            fscanf(fd, "%c\t%s\t%c\t%c\t%f\n",    
                &circuito[i].tipo,
                circuito[i].nome,  
                &circuito[i].NoM,        
                &circuito[i].Nom,
                &circuito[i].valor) != ".END" || ".end") //isto faz ate encontrar .end
        {
            i++;
        }
        fclose(fd);
    }
    else {
        printf("\nErro!");        
        system("cls");        
    }    

    return 0;    
}
解决方案

核心思路

移除全局结构体数组,改为在main函数内创建数组并通过指针传递给leitura函数,同时修复原代码中循环终止条件的逻辑错误(fscanf返回的是成功读取的变量数,无法直接与字符串比较)。

修改后的完整代码

#define _CRT_SECURE_NO_WARNINGS

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

typedef struct {      
    char tipo, NoM, Nom;    
    char nome[20];    
    float valor;    
} organ;

// 传入结构体数组指针+数组最大容量,避免越界
int leitura(organ *circuito, int max_size) {        
    FILE* fd;    
    char titulo[25];
    int i = 0;
    char line[100]; // 用于读取整行判断终止标记

    printf("Nome do Ficheiro: ");
    scanf("%s", titulo);
    getchar(); // 清除输入文件名后的换行符

    fd = fopen(titulo, "r");
    if (fd == NULL) { 
        printf("\nErro!");        
        system("cls");        
        return -1; // 返回错误码标识文件打开失败
    }

    // 跳过第一行标题
    while (fgetc(fd) != '\n' && !feof(fd));    

    i = 0;
    while (i < max_size) {
        // 读取整行数据
        if (fgets(line, sizeof(line), fd) == NULL) break;
        // 移除换行符
        line[strcspn(line, "\n")] = '\0';
        // 判断是否为终止标记
        if (strcmp(line, ".END") == 0 || strcmp(line, ".end") == 0) {
            break;
        }
        // 解析行内数据到结构体
        sscanf(line, "%c\t%s\t%c\t%c\t%f",    
            &circuito[i].tipo,
            circuito[i].nome,  
            &circuito[i].NoM,        
            &circuito[i].Nom,
            &circuito[i].valor);
        i++;
    }

    fclose(fd);
    return i; // 返回实际读取的元件数量
}

// main函数示例
int main() {
    organ circuito[7]; // 在main内声明结构体数组,无全局变量
    int elem_count = leitura(circuito, 7);
    // 后续可通过elem_count和circuito数组处理读取到的电路数据
    return 0;
}

关键改进点

  • 移除全局变量:结构体数组在main中创建,通过指针传递给leitura,彻底避免全局变量依赖。
  • 新增容量参数:传入max_size防止数组越界,提升代码安全性。
  • 修复终止逻辑:用fgets读取整行后判断终止标记,解决原代码中fscanf条件错误的问题。
  • 返回有效数据量:函数返回实际读取的元件个数,方便后续业务逻辑处理。

内容的提问来源于stack exchange,提问作者Lazytroll96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:45:57