I am trying to get a file name in C, at my project I will have three files, like Randomic%08d.txt, Inverted%08d.txt and Ordered%08d.txt, where this %08d represents the range I typed, if I typed range equal 3, the file name will be Randomic00000003.txt. I thought to get a file name just returning the file name at the functions in generateFiles.h but I guess that is not good to do because I will have change the return function type.
I want to get the file name because I will need to define a vector with the file data so I need to open the file.
main.c
#include <stdio.h>
#include "generateFiles.h"
int main(void) {
FILE *ordered, *inverted, *randomic;
int range, choice;
char fileName[255];
do {
printf("Menu\n\n");
printf("1 - Criar arquivos \n");
printf("2 - Ordenar usando Bubble Sort \n");
printf("3 - Ordenar usando Insertion Sort \n");
printf("4 - Fechar programa \n");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Informe o tamanho do arquivo: ");
scanf("%d", &range);
createOrderedFile(range, fileName, ordered);
createInvertedFile(range, fileName, inverted);
createRandomicFile(range, fileName, randomic);
break;
case 2:
fopen("Randomic%08d.txt", "r");
break;
}
} while(choice != 4);
}
generateFiles.h
#include <stdlib.h>
int INDEX = 0;
void createOrderedFile(int range, char fileName[255], FILE *ordered) {
int index;
sprintf(fileName, "Ordered%08d.txt", range);
ordered = fopen(fileName, "w");
for (INDEX = 1; INDEX <= range; INDEX++) {
fprintf(ordered, "%d\n", INDEX);
}
fclose(ordered);
}
void createInvertedFile(int range, char fileName[255], FILE *inverted) {
sprintf(fileName, "Inverted%08d.txt", range);
inverted = fopen(fileName, "w");
for (INDEX = range; INDEX >= 1; INDEX--) {
fprintf(inverted, "%d\n", INDEX);
}
fclose(inverted);
}
void createRandomicFile(int range, char fileName[255], FILE *randomic) {
sprintf(fileName, "Randomic%08d.txt", range);
randomic = fopen(fileName, "w");
for (INDEX = 1; INDEX <= range; INDEX++) {
fprintf(randomic, "%d\n", rand() % range + 1);
}
fclose(randomic);
}
Related
I was hoping to get a bit of help, I am implementing an inversion counter algorithm to take in 50,000 intergers and display the inversions and time it took to run the algorithm, I am having a hard time allocating and saving the integers from the file into an array. My code complies and runs but nothing happens
here is what I have:
int main(int argc, char** argv)
{
int n, i;
int inversions=0;
int *A;
FILE *file;
char filename[100];
clock_t start, end;
double totalTime;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if(file == NULL)
{
printf("Error opening file!\n");
return 0;
}
fscanf(file, "%d", &n);
A = (int*) malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
fscanf(file, "%d", &A[i]);
}
start = clock();
inversions = countInversionsBruteForce(A, n);
end = clock();
totalTime = (double) (end - start) / CLOCKS_PER_SEC;
printf("Brute Force Algorithm\n");
printf("Number of inversions: %d\n", inversions);
printf("Execution time: %f\n", totalTime);
I think I have noth allocated array size and saved it properly
Your program is incomplete so I was not able to compile it. Minimized the problem to just loading the data into your array:
Formatted code for readability.
Generated a suitable input file. Most likely this is your problem but you have not shared your input sample with us.
Added missing include files.
Remove argc, argv as you not using them.
Minimize scope of variables. Use size_t instead of int for unsigned values.
Max string size on obtaining file name
Check return value for scanf(), fopen(), fscanf().
Printing out the data read to demonstrate it's working.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Enter filename: ");
char filename[100];
if(scanf("%99s", filename) != 1) {
printf("scanf failed\n");
return 1;
}
FILE *file = fopen(filename, "r");
if(!file) {
printf("Error opening file!\n");
return 1;
}
size_t n;
fscanf(file, "%zu", &n);
if(!n) {
printf("n must be positive");
return 1;
}
int *A = malloc(n * sizeof(*A));
for(size_t i = 0; i < n; i++)
if(fscanf(file, "%d", &A[i]) != 1) {
printf("fscanf() failed\n");
return 1;
}
printf("n = %zu\n", n);
printf("A = ");
for(size_t i = 0; i < n; i++)
printf("%d%s", A[i], i + 1 < n ? ", " : "\n");
}
with 1.txt as:
4
1
2
3
4
a sample session looks like this:
Enter filename: 1.txt
n = 4
A = 1, 2, 3, 4
I was trying to make a code on C, which reads the file.txt, outputs it into console, and then counts rows, words etc, and after all is exporting the content of file.txt to file2.txt but in reverse order.
The text need to go from this:
I
Love
You
to this:
ouY
evoL
I
What I have in my text.file:
enter image description here
What i get with my code now:
enter image description here
Here is my code that's need improvement, because it prints the code how i need but with blank rows, which is not needed. And it needs to be exporting into another file also:
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
}
there's full code:
#include <stdio.h>
int main ()
{
FILE *fptr;
int i, n, j, pos;
char str[100];
char fname[20]="mfile.txt";
char newch[500];
int wrd=1,charctr=1,rows=1;
char str1;
char ch;
int no_lines = 1;
int COUNT = 0;
fptr = fopen(fname,"r");
if(fptr == NULL)
{
printf(" \n");
printf("File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf(" \n");
printf("The content of the file %s are: \n", fname);
printf(" \n");
while(ch != EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
if(ch=='\n')
{
rows++;
}
ch=fgetc(fptr);
}
int wrd1 = wrd - 1;
float charctr1 = charctr - 1;
float rows1 = rows;
float averageSymbol = charctr1 / rows1;
printf(" \n");
printf("\nwrd = %d, charctr = %d", wrd, charctr-1);
printf("\nThe number of rows in the file %s are : %d\n", fname,rows);
printf("\nThe average amount of symbols in a row is %f\n", averageSymbol);
printf(" \n");
}
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
}
fclose(fptr);
return 0;
}
Ok so if I understand correctly you want to get rid of some of the empty lines which show up in your code and then you want to also write the output of the program (the reversed text) into another file? I am assuming that you want the sentences to be also in the original order.
#include <stdio.h>
int main ()
{
FILE *fptr;
FILE *fptr2;
int i, n, j, pos;
char str[100];
char fname[20]="mfile.txt";
char fname2[20]="outputfile.txt";
char newch[500];
int wrd=1,charctr=1,rows=1;
char str1;
char ch;
int no_lines = 1;
int COUNT = 0;
fptr2 = fopen(fname2, "w+");
fptr = fopen(fname,"r");
if(fptr == NULL)
{
printf(" \n");
printf("File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf("The content of the file %s are: \n", fname);
while(ch != EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
if(ch=='\n')
{
rows++;
}
ch=fgetc(fptr);
}
int wrd1 = wrd - 1;
float charctr1 = charctr - 1;
float rows1 = rows;
float averageSymbol = charctr1 / rows1;
printf("\nwrd = %d, charctr = %d", wrd, charctr-1);
printf("\nThe number of rows in the file %s are : %d\n", fname,rows);
printf("The average amount of symbols in a row is %f\n", averageSymbol);
}
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
fputc(ch,fptr2);
}
fclose(fptr);
fclose(fptr2);
return 0;
}
This version first checks if a file called outputfile.txt exists and if no, it creates it. If said file already exists then the program overwrites the stuff which was originally in the file with the new program output (it doesn't clear the file all the way).
I'm trying to read a .txt file. The task is to read temperatures and give out min, max and average values. The txt file is called Temp.txt and it looks like this :
5 76 56 34 35 10
4 45 23 24 14
0
2 32 34
Here is the code that I've written. I have also tried to run it using just the file name like 'fopen("Temp.txt","r")' but I get the same result.
#include<stdio.h>
#include<string.h>
int ReadTempFile(FILE *fp, float temperatur[]);
float maxTemp(int anzahl, float temperatur[]);
float minTemp(int anzahl, float temperatur[]);
float mittlereTemp(int anzahl, float temperatur[]);
float fahrenheit(float celsius);
int ReadTempFile(FILE *fp, float temperatur[]) //For reading individual rows from txt file
{
int i=0;
fscanf(fp,"%f", &temperatur[0]);
for(i = 0; i < temperatur[0]; ++i)
{
fscanf(fp, "%f", &temperatur[i+1]);
}
return temperatur[0];
}
float maxTemp(int anzahl, float temperatur[]) //Maximum Temperature
{
int i = 0;
float max;
max = temperatur[i+1];
for(i = 1; i < anzahl; i++)
{
if(temperatur[i+1] > max)
{
max = temperatur[i+1];
}
}
return max;
}
float minTemp(int anzahl, float temperatur[]) //Minimum Temperature
{
int i = 0;
float min;
min = temperatur[i+1];
for(i = 1; i < anzahl; i++)
{
if(temperatur[i+1] < min)
{
min = temperatur[i+1];
}
}
return min;
}
float mittlereTemp(int anzahl, float temperatur[]) //Average Temperature
{
int i, sum = 0;
float mit;
for (i = 0; i <= anzahl; i++)
{
sum += temperatur[i];
}
mit = sum/temperatur[0];
return mit;
}
float fahrenheit(float celsius) //Celsius to Fahrenheit
{
float f;
f = (celsius*9/5) + 32;
return f;
}
int main()
{
int end, n, Zeile=1;
float temperatur[20], max, min, mit, fmax, fmin, fmit;
char eingabe[20];
FILE *fp=NULL;
do
{
printf("Enter File name: \n"); //Enter file name
fflush(stdout);
scanf("%s", eingabe);
fp = fopen(eingabe, "r" );
if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe); //Error message for File cant be opened
}while(fp != NULL);
do{
n = ReadTempFile(fp, temperatur);
max = maxTemp(n, temperatur);
printf("Das Maximum der Zeile %d ist: %.3fC \t",Zeile, max);
fmax = fahrenheit(max);
printf("In Fahrenheit: %.3fF\n", fmax);
min = minTemp(n, temperatur);
printf("Das Minimum der Zeile %d ist: %.3fC \t",Zeile, min);
fmin = fahrenheit(min);
printf("In Fahrenheit: %.3fF\n", fmin);
mit = mittlereTemp(n, temperatur);
printf("Der Mittelwert der Zeile %d ist: %.3fC \t",Zeile, mit);
fmit = fahrenheit(mit);
printf("In Fahrenheit: %.3fF\n", fmit);
++Zeile;
end = feof(fp);
printf("\n\n");
}while (end == 0);
fclose(fp);
return 0;
}
This is what happens after I run the above program.
Thank you in advance.
The most immediate problem that is likely causing the crash is the logic for opening a file:
do
{
printf("Enter File name: \n"); //Enter file name
fflush(stdout);
scanf("%s", eingabe);
fp = fopen(eingabe, "r" );
if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe);
}while(fp != NULL); // <- Loops until it fails
This will guarantee that the loop will not end until a file fails to open. When you later try to fscanf from fp set to NULL, you'll have undefined behavior (and this may manifest itself as a crash).
Suggested fix:
for(;;) {
puts("Enter File name:");
if(scanf("%19s", eingabe) == 1) { // make sure scanf succeeds
fp = fopen(eingabe, "r" );
if(fp) break; // break out when it succeeds to open
perror(eingabe);
} else {
fprintf(stderr, "Error: No filename entered.\n");
return 1;
}
}
Note: In your example-run, you showed that you entered Temp to open Temp.txt. You must enter Temp.txt to successfully open Temp.txt.
Here is your program with some other fixes too. I've commented inline so you see why I suggest the changes.
Notes:
I've removed the +1 offset in temperatur completely. You shouldn't use the first float to store the count of temperatures which is an integer value.
Your mittlereTemp didn't use this offset, so it gave the wrong answers too.
mittlereTemp didn't calculate the median temperature (which I think "mittlereTemp" means). It tried to calculate the average temperature, so I changed the name to durchschnittsTemp.
#include <math.h>
#include <stdio.h>
#include <string.h>
// For reading individual rows from txt file
// max_anzahl added to not try to read too many
int ReadTempFile(FILE* fp, float temperatur[], int max_anzahl) {
int count;
// return -1 on failure
if(fscanf(fp, "%d", &count) != 1) return -1;
// we can't read all the entries if count > max_anzahl
if(count > max_anzahl || count < 0) return -1;
for(int i = 0; i < count; ++i) {
if(fscanf(fp, "%f", &temperatur[i]) != 1) {
return -1; // could not read count floats, failure
}
}
return count;
}
// The idiomatic way is to have the array pointer first and
// the count second so I swapped the order of temperatur and anzahl:
float maxTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no max temp
float max = temperatur[0];
for(int i = 1; i < anzahl; i++) {
if(temperatur[i] > max) {
max = temperatur[i];
}
}
return max;
}
float minTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no min temp
float min = temperatur[0];
for(int i = 1; i < anzahl; i++) {
if(temperatur[i] < min) {
min = temperatur[i];
}
}
return min;
}
// I changed the name to durchschnittsTemp
float durchschnittsTemp(float temperatur[], int anzahl) {
if(anzahl == 0) return NAN; // if we have no values, we have no average temp
float sum = 0.f; // use the proper type for sum
for(int i = 0; i < anzahl; i++) {
sum += temperatur[i];
}
return sum / (float)anzahl;
}
float fahrenheit(float celsius) {
float f;
f = (celsius * 9 / 5) + 32;
return f;
}
// since opening the file is a lot of code, make a function
FILE* open_file_supplied_by_the_user() {
char eingabe[FILENAME_MAX]; // make plenty of room for the filename
for(;;) {
puts("Enter File name:");
// use fgets instead of scanf to make it easier to read filenames with spaces
if(fgets(eingabe, sizeof eingabe, stdin)) {
size_t len = strlen(eingabe);
eingabe[len - 1] = '\0';
FILE* fp = fopen(eingabe, "r");
if(fp) return fp; // break out when it succeeds to open
perror(eingabe); // give the user a proper error message
} else {
fprintf(stderr, "Error: No filename entered.\n");
return NULL;
}
}
}
#define Size(x) (sizeof(x) / sizeof *(x))
int main() {
FILE* fp = open_file_supplied_by_the_user();
if(fp == NULL) return 1; // exit if no file was opened
float temperatur[20];
// loop until ReadTempFile() returns -1 (failure)
for(int n, Zeile = 1;
(n = ReadTempFile(fp, temperatur, Size(temperatur))) != -1;
++Zeile)
{
float max = maxTemp(temperatur, n);
printf("Das Maximum der Zeile %d ist: %.3fC \t", Zeile, max);
printf("In Fahrenheit: %.3fF\n", fahrenheit(max));
float min = minTemp(temperatur, n);
printf("Das Minimum der Zeile %d ist: %.3fC \t", Zeile, min);
printf("In Fahrenheit: %.3fF\n", fahrenheit(min));
float mit = durchschnittsTemp(temperatur, n);
printf("Der Durchschnittswert der Zeile %d ist: %.3fC \t", Zeile, mit);
printf("In Fahrenheit: %.3fF\n", fahrenheit(mit));
printf("\n\n");
}
fclose(fp);
}
I am trying to rewrite text in files, changing first line by +1(that holds number of struct saved in igraci.txt) This part is working fine. Then rewrite all text that was there before(This is also working fine) and in the end add 2 new lines in text. Problem is in the last code i wrote here
These are some global variables that I am having problem with and strcture
int RijeciBroj = 0;
int IgraciBroj = 0;
typedef struct Igrac
{
char ime[20];
int brojPoena;
};
This is method for allocating memmory for structures having in mind that one strcture is going to be added
struct Igrac* napraviProstor(int n) {
IgraciBroj = n; //here I try to give global new value
printf("U NAPRAVI PROSTOR : %d", IgraciBroj); // Here i get -9282928
return (struct Igrac*) malloc((n + 1) * sizeof(struct Igrac));
}
This is method that is reading text from file and storing it in allocated memory
void ucitajIgrace(struct Igrac *arr) {
static const char filename[] = "igraci.txt";
FILE *file;
file = fopen(filename, "r");
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
int i = -1;
int k = 0;
fgets(line, 20, file);
while (fgets(line, 20, file) != NULL) /* read a line */
{
line[strcspn(line, "\n")] = '\0';
i++;
if (i == 0) {
strcpy((arr + k)->ime, line);
}
if (i == 1) {
(arr + k)->brojPoena = atol(line);
k++;
i = -1;
}
}
printf("Igraca: %d", IgraciBroj); //here i get -9892827280
fclose(file);
}
else
{
perror(filename);
}
}
Main method
int main()
{
int o;
Igrac *igr;
FILE *file1;
file1 = fopen("igraci.txt", "r");
if (file1 != NULL)
{
char line[20];
fscanf(file1, "%d", &o); //first line is number of structs
igr = napraviProstor(o);
ucitajIgrace(igr);
}
pocniIgru(rijeci,igr); //ignore rijeci that is another array that is working perfect and has nothing to do with my problem
return 0;
}
This is method where I have problem
void pocniIgru(char** rijeci, struct Igrac *igraci) {
int dobijeni[5] = {}; //array that is saving random numbers so they don't repeat
int brojac1 = 0; //used for index of dobijeni[5]
char srpska[30]; // for user input
char ime[20]; //for users name that we are going to store in igraci.txt
int poeni = 0; //number of points
bool moze; //boolean for loop control
printf("Pocinje igra\n");
printf("\n\n\n\n");
int pitanje; // for random number that we are going to get
for (int i = 0; i < 5; i++) {
moze = true;
LOOP:do {
srand(time(NULL));
pitanje = rand() % RijeciBroj-1; //random number between 0 - global variable here global variable is working fine!
if (pitanje % 2 != 0) {
pitanje++; // I need even number and 0 is accepted
}
for (int k = 0; k < 5; k++) {
if (dobijeni[k] == pitanje) { //checking if we arleay had that number
goto LOOP; // goto LOOP if we had that number so we pick another
}
}
dobijeni[brojac1] = pitanje; //storing that number in loop for later check so it won't repeat
moze = false; // do-while stops
brojac1++;
} while (moze);
printf("Engleska rijec je: %s", rijeci[pitanje]); //get word from array
printf("Unesite rijec na srpskom jeziku: ");
scanf("%30s", srpska); //user input for comparing
strtok(rijeci[pitanje + 1], "\n"); //we need to remove newline
if (strcmp(rijeci[pitanje+1], srpska) == 0) { //cheking if next word is same with user input
poeni += 2;
printf("Tacno! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
else {
poeni -= 1;
if (brojac != 5) {
printf("Greska! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
}
}
printf("Ukupan broj poena je: %d\n", poeni);
printf("Unesite svoje ime: "); //Enter your name
scanf("%s", ime); //get name
if (strcmp(ime, "")) { //check if it's empty
IgraciBroj += 1; //global variable +1 for rewriting in file
strcpy((igraci + IgraciBroj)->ime, ime); //save name in char* struct in last place that is empty
(igraci + IgraciBroj)->brojPoena = poeni; //save points in char* struct in last place that is empty
printf("%s osvojili ste %d poena", (igraci + IgraciBroj)->ime, (igraci + IgraciBroj)->brojPoena); //Here i get normal result and name
FILE *file1;
file1 = fopen("igraci.txt", "w");
if (file1 != NULL)
{
fprintf(file1, "%d\n", IgraciBroj);
for (int broj = 0; broj < IgraciBroj; broj++) {
fprintf(file1, "%s\n", (igraci + broj)->ime); //Problem !! I get some lines before name in file example(----------Name)
fprintf(file1, "%d\n", (igraci + broj)->brojPoena); //Problem !! I get some number like -9899887
}
}
}
The following program creates a new dat file and stores random data. Then one of the values is searched from the file and printed.
The problem is data up to 13 items are searched and the program exits. As shown in following picture 100 inputs are stored and only 13 items are searched. What is the solution?
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
int recordsize = sizeof(det); // size of record
FILE *fp1 = fopen("random.dat", "a+");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
fwrite(&det, recordsize, 1, fp1);
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
scanf("%d", &number);
fseek(fp1, 0, SEEK_SET); // move file position indicator to beginning of file
do {
countNumber++; // counts number of times the file is searched
fread(&buffer, recordsize, 1, fp1);
if (buffer.rollNo == number) {
stat = 1;
break;
}
} while (!feof(fp1));
printf("\n");
if (stat) {
printf("succesfully found at %d\n", countNumber);
printf(" roll number %d\n regd number %d\n salary %d\n status %d\n",
buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
} else
printf("there is no such roll number %d in the list\nlength of list : %d\n",
number, countNumber);
fclose(fp1);
}
The output is:
The code works fine on my system, but there are possible problems:
you open the binary file in default mode, possibly text mode. Use "ab+" instead.
the file is open in append mode. If it contains invalid data, especially if its size is not a multiple of the size of the record size, appended records will not be properly aligned, and thus will not be read back correctly.
test the success of the scanf(), fwrite() and fread() calls
the end of file test is incorrect.
Here is an improved version:
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
int recordsize = sizeof(det); // size of record
FILE *fp1 = fopen("random.dat", "ab+");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
if (scanf("%d", &n) != 1)
return 1;
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
if (fwrite(&det, recordsize, 1, fp1) != 1) {
perror("cannot write record");
fclose(fp1);
return 2;
}
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
if (scanf("%d", &number) != 1)
return 1;
fseek(fp1, 0, SEEK_SET); // move file position indicator to beginning of file
while (fread(&buffer, recordsize, 1, fp1) == 1) {
countNumber++; // counts number of times the file is searched
if (buffer.rollNo == number) {
stat = 1;
break;
}
}
printf("\n");
if (stat) {
printf("successfully found at %d\n", countNumber);
printf(" roll number %d\n"
" regd number %d\n"
" salary %d\n"
" status %d\n",
buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
} else {
printf("there is no such roll number %d in the list\n"
"length of list : %d\n",
number, countNumber);
}
fclose(fp1);
return 0;
}
Your main problem is that your store binary data where system expect you to store text, see this question.
fopen(..., "a+"); open a file for text reading, but you store binary data in it
You have some other issues:
You don't use feof the right way
Your main function does not return value,
You do not test the value of n or number.
Corrected code should looks like:
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
/* open the file in BINARY mode */
FILE* fp1 = fopen("random.dat" , "a+b");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
if (1 != fwrite(&det, sizeof det, 1, fp1)) {
perror("fwrite");
return 2;
}
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
scanf("%d", &number);
fseek(fp1, 0, SEEK_SET); // rewind would have done the job
while (1) {
countNumber++; // counts number of times the file is searched
if (1 != fread(&buffer, sizeof buffer, 1, fp1)) {
perror("fread");
return 3;
}
if (buffer.rollNo == number) {
stat = 1;
break;
}
}
printf("\n");
if (stat) {
printf("succesfully found at %d\n", countNumber);
printf(" roll number %d\n regd number %d\n salary %d\n status %d\n", buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
}
else
printf("there is no such roll number %d in the list\nlength of list : %d\n", number, countNumber);
/* warning: file is not closed in case of error... */
fclose(fp1);
return 0;
}