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

运行时检查失败#2 – 变量’filename’周围的堆栈已损坏。

每当我尝试处理第一个内存位置时,我的代码都有效。 我可以正确处理.txt文件,我可以打印它。 然而,当我要求第二个内存位置时,程序崩溃了。 我试图增加文件名的大小,我也关闭了第一个文件,所以我很无能为力。 任何帮助都可以接受! 谢谢!!

这是输出的照片

这是我的代码:

#include  #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); } } } 

正如马丁詹姆斯所说char dummy1[1]; 是一个绝对的禁忌。

使用fgets()而不是gets() ,而不是

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

尝试,

fgets( filename, sizeof(filename) , stdin );