【发布时间】:2021-05-10 03:43:31
【问题描述】:
我正在尝试用 C 语言读取文件并将数据存储在数组中,它运行良好,但我不希望程序在关闭文件后完成
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
char TimeDat[24][8] ;
float TempArr [2][24];
float HumiArr[24];
float MotionArr[6][24];
void ReadDataFile(char *location,char device_location [10],int line);
void get_menu();
int main( )
{
while(1)
{
get_menu();
}
return 0;
}
void get_menu()
{
char chosen_name [10] ;
int menu_option;
printf("Choose your task : \n");
printf("1 - Read files by name : \n");
scanf ("%d",&menu_option);
if (menu_option==1)
{
printf("Enter Your file name : Bedroom , Kitchen , LivingRoom \n");
scanf ("%s",&chosen_name);
if (strcmp(chosen_name,"Bedroom") == 0)
{
char * Bedroom_file_location="Bedroom.txt";
ReadDataFile(Bedroom_file_location ,"Bedroom",24);
}
else if (strcmp(chosen_name,"Kitchen") == 0)
{
char * Kitchen_file_location="Kitchen.txt";
ReadDataFile(Kitchen_file_location ,"Bedroom",24);
}
else if (strcmp(chosen_name,"LivingRoom") == 0)
{
char * LivingRoom_file_location="LivingRoom.txt";
ReadDataFile(LivingRoom_file_location ,"Bedroom",24);
}
}
else if (menu_option==2 )
{
}
}
void ReadDataFile(char *location,char device_location [10],int line) {
printf("this is a %s \n",device_location);
int read_status=0;
int t,k;
FILE *fp; // assign to the file location
fp = fopen(location, "r");
if(fp == NULL)
{
printf("Error!\n");
//exit(1);
}
t=0;
while(line--){
fscanf(fp, "%s", &TimeDat[t]);
fscanf(fp, "%f%f", &TempArr[t][0], &TempArr[t][1]);
fscanf(fp, "%f", &HumiArr[t]);
for ( k=0; k<6; k++)
{
fscanf(fp,"%f", &MotionArr[t][k]);
}
printf(" :%s ",TimeDat[t]);
printf(" : %f , %f ",TempArr[t][0],TempArr[t][1]);
printf(" : %f ",HumiArr[t]);
printf(" : %f , %f , %f , %f , %f , %f",MotionArr[t][0],MotionArr[t][1],MotionArr[t][2],MotionArr[t][3],MotionArr[t][4],MotionArr[t][5]);
printf(" \n");
t++;
}
fclose(fp);
main();
}
我的输出是 100% 正确的,但我收到了这条消息:
Process returned -1073741571 (0xC00000FD) execution time : 6.531 s
Press any key to continue.
我正在尝试返回菜单,以便用户可以打开另一个文件或执行其他一些选项。 我会感谢你的帮助 提前感谢
【问题讨论】:
-
不知道它是否能解决您的问题,但不要致电
main。让ReadDataFile返回,get_menu返回,然后你回到main,回到你的无限循环。在ReadDataFile中调用main将永远不会让这些函数中的任何一个返回,并且您的进程将继续消耗内存和堆栈空间。 -
您的
chosen_name字符数组太小。您期望的最长字符串是LivingRoom,即 10 个字符。但是有一个\0被scanf放在末尾,可能会污染以下变量(menu_option)。另外,如果有人输入了更长的字符串,scanf将会把你的堆栈搞得一团糟。 -
我尝试在关闭文件“fclose(fp);”后调用 get_menu但我有同样的结果
-
肯定和文件读取过程有关
标签: c file codeblocks