C语言中从非main函数返回文件指针至main并传递给其他函数
解决方案:在C中跨函数传递文件指针
核心思路
C语言中文件操作依赖FILE*指针实现。你可以让第一个函数返回打开的FILE*指针,在main中接收后,直接将该指针作为参数传给第二个函数即可。需要重点处理文件打开失败的情况,以及后续的资源释放(关闭文件、释放动态数组内存)。
完整示例代码
#include <stdio.h> #include <stdlib.h> #include <string.h> // 自定义函数1:打开指定路径的文件,返回FILE*指针 FILE* open_file(const char* filename) { FILE* fp = fopen(filename, "r"); if (fp == NULL) { perror("Failed to open file"); } return fp; } // 自定义函数2:从文件读取内容到两个动态数组(示例读取整数和字符串) // 用指针的指针传递动态数组,方便函数内修改数组地址(扩容场景) int read_file_to_arrays(FILE* fp, int** int_array, char*** str_array, size_t* count) { *count = 0; size_t capacity = 4; // 初始容量,可按需调整 // 初始化动态数组 *int_array = malloc(capacity * sizeof(int)); *str_array = malloc(capacity * sizeof(char*)); if (*int_array == NULL || *str_array == NULL) { perror("Failed to allocate memory"); return -1; } int num; char buffer[256]; // 按行读取(假设每行是整数+字符串,空格分隔) while (fscanf(fp, "%d %s", &num, buffer) == 2) { // 容量不足时扩容 if (*count >= capacity) { capacity *= 2; int* temp_int = realloc(*int_array, capacity * sizeof(int)); char** temp_str = realloc(*str_array, capacity * sizeof(char*)); if (temp_int == NULL || temp_str == NULL) { perror("Failed to reallocate memory"); // 出错时清理已分配内存 free(*int_array); free(*str_array); return -1; } *int_array = temp_int; *str_array = temp_str; } // 存储整数 (*int_array)[*count] = num; // 存储字符串(单独分配内存复制内容) (*str_array)[*count] = malloc(strlen(buffer) + 1); if ((*str_array)[*count] == NULL) { perror("Failed to allocate memory for string"); // 清理已分配的字符串内存 for (size_t i = 0; i < *count; i++) { free((*str_array)[i]); } free(*int_array); free(*str_array); return -1; } strcpy((*str_array)[*count], buffer); (*count)++; } // 检查读取是否因错误中断(非EOF) if (!feof(fp)) { perror("Error reading file"); // 清理资源 for (size_t i = 0; i < *count; i++) { free((*str_array)[i]); } free(*int_array); free(*str_array); return -1; } return 0; } int main() { const char* filename = "test.txt"; // 调用打开文件的函数 FILE* fp = open_file(filename); if (fp == NULL) { return EXIT_FAILURE; } int* int_array = NULL; char** str_array = NULL; size_t count = 0; // 将文件指针传入读取函数 if (read_file_to_arrays(fp, &int_array, &str_array, &count) != 0) { fclose(fp); return EXIT_FAILURE; } // 示例:打印读取结果 printf("Read %zu items:\n", count); for (size_t i = 0; i < count; i++) { printf("%d: %s\n", int_array[i], str_array[i]); } // 释放资源:先释放字符串元素,再释放数组,最后关闭文件 for (size_t i = 0; i < count; i++) { free(str_array[i]); } free(int_array); free(str_array); fclose(fp); return EXIT_SUCCESS; }
关键细节说明
- 文件指针传递:
open_file返回的FILE*是指向文件对象的指针,main接收后传给第二个函数,本质是传递指针副本,但指向同一个文件对象,因此能正常操作文件。 - 动态数组处理:由于扩容时需要修改数组的内存地址,所以必须用指针的指针(
int**、char***)作为函数参数。 - 错误处理:每个可能失败的步骤(打开文件、内存分配、读取)都做了检查,避免程序崩溃或内存泄漏。
- 资源释放:所有手动分配的内存必须逐一释放,文件使用完毕后必须调用
fclose关闭。
内容的提问来源于stack exchange,提问作者wictor33
相关产品推荐
相关产品推荐

