gpt4 book ai didi

c - C 文件处理中的运行时检查失败 #2

转载 作者:行者123 更新时间:2023-11-30 15:14:42 25 4
gpt4 key购买 nike

运行时检查失败#2 - 变量“文件名”周围的堆栈已损坏。

每当我尝试处理第一个内存位置时,我的代码都会工作。我可以正确处理 .txt 文件,并且可以打印它。然而,当我请求第二个内存位置时,程序崩溃了。我尝试增加文件名的大小,并且我还关闭了第一个文件,所以我一无所知。任何帮助都是可以接受的!谢谢!!

This is a photo of the output

这是我的代码:

#include <stdio.h>

#define SIZE 100 //100 entries (100lines on a file)
#define SENSORN 100

int main()
{
FILE *fptr;
char filename[1000];

char dummy1[1];//dummy character that help me to erase what is the buffer when using gets()
int numberOfSensors;
int time[SENSORN][SIZE];
float powerConsumption[SENSORN][SIZE];

int sensor_num;
int count1 = 0;

printf("Please enter the number of sensors: ");
scanf("%d", &numberOfSensors);

//Asking for the link
//numberOfSensors - 1 because for example, if we want only 2 sensors we need sensor0 and sensor1 only
for (sensor_num = 0; sensor_num <= (numberOfSensors - 1); sensor_num++)
{
printf("Please enter the file location for sensor %d\n", sensor_num);
gets(dummy1);//clearing the buffer
gets(filename);

fptr = fopen(filename, "r");

//if file cannot be opened, then display and error message
if (fptr == NULL)
{
printf("Error opening the file! %s \n", filename);
printf("Please restart the program \n");
return 0; //exit the program
}

else
{
//Loop that let us read and print all the file by storing each value to its respective array

while (!feof(fptr))
{
//storing all the values in their respective array
//sensor_num is the sensor number
//count1 is the line number we are reading from the file
fscanf(fptr, "%d %f", &time[sensor_num][count1], &powerConsumption[sensor_num][count1]);

//making sure we have all the values stored
//Note: do not comment the following line in order to check that all values are stored
fprintf(stdout, "%d %6.2f \n", time[sensor_num][count1], powerConsumption[sensor_num][count1]);
count1++;
}
}
//closing file
fclose(fptr);
}
}
}

最佳答案

正如 Martin James 所说,char dummy1[1]; 是绝对禁忌。

使用fgets()代替gets(),因此代替

gets(dummy1);//clearing the buffer
gets(filename);`

尝试,

fgets( 文件名, sizeof(文件名) , stdin );

关于c - C 文件处理中的运行时检查失败 #2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33968927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com