Run-Time Check Failure #2 - Stack around the variable 'filename' was corrupted.
My code works whenever I try to process the first memory location.
I can process the .txt file correctly, and I can print it.
Nevertheless, when I ask for a second memory location, the program crashes.
I tried to increase the size of filename, and I am also closing the first file, so I am clueless. Any help is acceptable! Thank you!!
This is a photo of the output
This is my code:
#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);
}
}
}
As Martin James said char dummy1[1]; is an absolute no-no.
Use fgets() instead of gets(), so instead of
gets(dummy1);//clearing the buffer
gets(filename);`
try,
fgets( filename, sizeof(filename) , stdin );
Related
i'm new here and i'm trying to solve a FILE problem in c. Basically i have to create a program that lets the user input how many lines he wants to write in a file, create a new file, write those lines and the reading it and establish how many lines where written and print the number of lines.
int main() {
int x, lc=0;
char str[100];
FILE *fp=fopen("test.txt","w");
if (fp==NULL) {
printf("\nOpening failed");
}else{
printf("\nOpened correctly");
}
printf("\nStrings to write:\n");
scanf("%d",&x);
for (int i = 0; i < x; i++) {
fgets(str, sizeof str, stdin);
fputs(str,fp);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL) {
lc++;
}
fclose(fr);
printf("\nThere are %d lines",lc);
return 0;
}
If i leave the code like this it messes up with my for cycle and it only lets me write 3 lines because it does put a free line at the start of the file. Can you explain how do i solve that? or if it's just how fgets and fputs behave and i have to remember that blank line at the start. Thank you in advance. (i'll leave a file output as follows with numbers for the lines)
1)
2)it seems to work
3)dhdhdh dhdh
4)random things
As you can tell from the comments, there are a lot of ways to approach this task. The usage of "scanf" and "fgets" can get complex especially if mixed within the same reading task. But, just to give you one option as to deriving a solution, following is a snippet of code to offer one of many possible routes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x, lc=0;
char str[101];
FILE *fp=fopen("test.txt","w");
if (fp==NULL)
{
printf("Opening failed\n");
}
else
{
printf("Opened correctly\n");
}
printf("Strings to write: ");
scanf("%d",&x);
for (int i = 0; i < x; i++)
{
printf("Enter string: ");
scanf("%s", str);
fprintf(fp, "%s\n", str);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL)
{
lc++;
}
fclose(fr);
printf("\nThere are %d lines\n",lc);
return 0;
}
You will note that both "scanf" and "fgets" are being used in this example, but not in reference to the same file. For user input, "scanf" is getting used. Once the file is closed and then reopened for reading, "fgets" is being used for that portion of the task.
Testing this program snippet out resulted in matching up the same quantity of lines read from the file as were entered.
#Una:~/C_Programs/Console/FileWrite/bin/Release$ ./FileWrite
Opened correctly
Strings to write: 4
Enter string: Welcome
Enter string: to
Enter string: Stack
Enter string: Overflow
There are 4 lines
Give it a try and see if it meets the spirit of your project.
This question already has answers here:
Why is “while( !feof(file) )” always wrong?
(5 answers)
Closed last year.
can I know why the last line of the table below will print twice? Everything is executed well and just has the problem stated above.
The type of file used is a random access file and data written into a binary file named toyota.txt.
Anyone can teach me what is the problem there? Thank you so much!
The code is shown below:
/*program 1 write the data into file toyota.txt*/
#include<stdio.h>
struct vehicledata{
char vnum[100];
int cnum;
float f50;
float f100;
float f200;
float f400;
float f800;
};
int main()
{
FILE *fptr;
struct vehicledata toyota;
if((fptr = fopen("toyota.txt","wb")) == NULL)
{
printf("Error! File fail opened!");
}
else
{
printf("This program can create a text file named toyota.txt \n");
printf("and save the value of car noise level(dB) with\ndifferent frequency and vehicle numbers into file\n\n");
printf("======================================================================\n");
printf("Enter car number(1 to 10, enter 0 to end input)\n");
printf("? ");
scanf("%d", &toyota.cnum);
while (toyota.cnum != 0)
{
printf("\nEnter Vehicle number\n");
printf("? ");
scanf("%s", toyota.vnum);
printf("Enter car noise level(dB) at 50Hz, 100Hz, 200Hz, 400Hz and 800Hz\n");
printf("? ");
scanf("%f %f %f %f %f", &toyota.f50, &toyota.f100, &toyota.f200, &toyota.f400, &toyota.f800);
fseek(fptr, (toyota.cnum - 1) * sizeof(struct vehicledata), SEEK_SET);
fwrite(&toyota, sizeof(struct vehicledata), 1, fptr);
printf("\n======================================================================\n");
printf("\nEnter car number (1 to 100, 0 to end input) \n");
printf("? ");
scanf("%d", &toyota.cnum);
}
}
fclose(fptr);
return 0;
}
/*program 2 reads the data from the file toyota.txt and find
the car that emanates the minimum noise at 200Hz*/
#include <stdio.h>
#include <stdlib.h>
struct vehicledata{
char vnum[100];
int cnum;
float f50;
float f100;
float f200;
float f400;
float f800;
};
char name[10];
float min;
int i, m;
int main()
{
FILE *fptr;
struct vehicledata toyota;
if ((fptr = fopen("toyota.txt","rb")) == NULL)//open and read data in the file
{
printf("Error! File fail opened!");
}
else
{
printf("This program can read and display the data from the toyota.txt\n and find car that have minimum noise in 200Hz\n\n");
printf("\nThe information in the toyota.txt are shown at below:\n");
printf("\n\t\t\t\tCar Noise Level(dB)\t\t\t");
printf("\n=======================================================================\n");
printf("%s\t\t%s\t%s\t%s\t%s\t%s\t\n","Vehicle Number","50Hz","100Hz","200Hz","400Hz","800Hz");
printf("=======================================================================\n");
char name[10];
float min=100;
while(!feof(fptr))
{
fread(&toyota, sizeof(struct vehicledata), 1, fptr);
if(toyota.f200 < min)
{
min=toyota.f200;
for(int i=0 ; i<10 ; i++)
{
name[i]=toyota.vnum[i];
}
}
if(toyota.cnum != 0)
{
printf("%s\t\t\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", toyota.vnum, toyota.f50, toyota.f100, toyota.f200, toyota.f400, toyota.f800);
}
}
printf("=======================================================================\n");
printf("\n\n+++++++++++++++++++++++++++++++++Result+++++++++++++++++++++++++++++++++\n");
printf("\nVehicle number of car with minimum noise in 200Hz is %s at %.2f dB\n", name, min);
}
fclose(fptr);
return 0;
}
The problem is in program 2. In the section below you assume that your fread will be OK since you are not att the EOF. This is not the case.
while(!feof(fptr))
{
fread(&toyota, sizeof(struct vehicledata), 1, fptr);
What happens is that you check for EOF in your loop and being at the very end of the file the last fread is indeed read one more time but fails. Since you don't check for it and fread did not have toyota overwritten (since the read failed) you have a duplicate that you print out. After that you now check for EOF and leave the loop.
A better loop would look like this:
while (fread(&toyota, sizeof(struct vehicledata), 1, fptr)) {
Since the documentation for fread states, "If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).", in your case we are not really checking for errors and we are at EOF.
But if you want to figure out that the loop ended due to EOF or an error then "callers must use feof(3) and ferror(3) to determine which occurred.".
I am trying to read employee information from the user and enter it into a file using fwrite() function and later i want to print the data contents on the screen using fread() to read from file and then print it.
When i am inside the program, this process is working absolutely fine but after program is exited and i access the file where the information has been stored, i see unreadable characters but in the program they are printed as normal english characters and digits.
Here is my code:
#include<stdio.h>
struct emp{
int id;
char name[30];
double salary;
}S;
void main(){
char fname[60];
printf("Enter file name: ");
scanf("%s", fname);
FILE *fptr = fopen(fname, "a+"); // open file in append + mode, create if not found.
if(fptr == NULL){
printf("Some error occured !\n");
return;
}
int i, size;
printf("Enter the number of employees whose information is needed to be added to the file: ");
scanf("%d", &size);
// writing
for(i = 0 ; i < size ; i++){
printf("Employee %d:\n", i+1);
printf("Enter id: ");
scanf("%d", &S.id);
printf("Enter name: ");
while(getchar() != '\n'); // clear buffer
scanf("%s", S.name);
printf("Enter salary: ");
scanf("%lf", &S.salary);
fwrite(&S, sizeof(struct emp), 1, fptr);
printf("----------------------------------------\n");
}
rewind(fptr); // move pointer to first record in file
// reading
printf("File contents: \n");
printf("ID\t\tNAME\t\tSALARY\n");
while(fread(&S, sizeof(struct emp), 1, fptr) != 0){
printf("%d\t\t%s\t\t%lf\n", S.id, S.name, S.salary);
}
}
Here is the picture of what i am trying to expalin.
You are writing to the file the struct and not printing its contents separately. It works when you read it back, but when you open the file, it simply doesn't know what it is (you have int and char* and double in your struct.
If you want to visualize it on the file, you need to print each term of the struct individually, and read it back the same way, in order to see it on screen.
Using C, I am trying sum up the numbers in a file. The file contains numbers such as:
123
456
788
...
356
When running the code, it properly asks for input and prints the number I enter. However, it does not sum the file, and just displays an unrecognized character symbol, like a small ?. I don't think the number is over the alloted INT_MAX_SIZE. What seems to be the issue?
#include <stdio.h>
main() {
//Number variable to assign each line to
int c;
int fds[2];
int childid;
int size;
int number;
int sum;
printf ("Enter the number of processes to create: ");
scanf ("%d", &number);
printf ("You entered: %d", number);
printf("\n");
//File I/O operations
FILE *file;
//Open file for reading
file = fopen("Project1_OS/project1_data/file1.dat", "r");
//If file is found
if (file) {
//While file has data to be read
while ((c = getc(file)) != EOF)
//Print data
//putchar(c);
sum+=c;
//Close the file I/O
fclose(file);
}
putchar(sum);
}
first getc it's a function for reading characters from a file not integers .
you have to use fscanf :
fscanf(file,"%3d",&c)
second putchar it's a function for printing characters not intgers .
so you have to write :
printf("%d",sum);
I want to read from a file ints and floats, and then I want to store them in a two dimensional array.
Let say I have a file with two columns. First column integers, and second column floats. Let say I have a 20 row
define SIZE 100 //100 entries (100lines on a file)
define SENSORN 10
This is my code:
FILE *fptr;
char filename[100];
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);
printf("NOTE: use double backslashes to enter file location \n");
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++;
}
}
}
It looks like it is reading my file, but when I debug it only stores garbage on my arrays. Can somebody explains me what is wrong with this?
Thank you so much! :D