Why am I receiving "Segmentation fault: 11" - c

When I go to run this within my terminal it will simply tell me it is a segmentation fault. This program reads in a file called DATA. This is a txt file that contains exam scores. The scores go as following (if at all relevant): 10 25 50 50 5 0 0 45 45 15 25 50 2 50 30 40.
#include <stdio.h>
int main()
{
FILE *fp = fopen("DATA", "r"); //Opens the file DATA in read mode.
int possibleScoreCounts[51] = {0};
int score;
while(!feof(fp))
{
fscanf(fp, "%d", &score);
possibleScoreCounts[score]++;
}
printf("Enter a score to check on the exam: ");
scanf("%d", &score);
while(score != -1)
{
int count = 0;
for(int i = 0; i < score; i++)
count = count + possibleScoreCounts[i];
printf("%d scored lower than %d\n", count, score);
printf("Enter a score to check on the exam: ");
scanf("%d", &score);
}
}

your code compiles under c99 to compile it with out move i declatration outside the for
I tested this on my system and it works (as far as logic goes)
This means that one of the specific functions fopen, fscanf, or scanf failes - you must check error values

Related

Want a C program to write into a file, read it and store even and odd numbers in a separate file

I tried to make the following code.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2,*fp3;
int n,i,size;
printf("Enter no.of digits: ");
scanf("%d",&size);
fp1=fopen("NUMBER.txt","w");
printf("Enter the numbers: \n");
for(i=0;i<size;i++)
{
fflush(stdin);
scanf(" %d",&n);
fputc(n,fp1);
}
fclose(fp1);
fp1=fopen("NUMBER.txt","r");
fp2=fopen("EVEN.txt","w");
fp3=fopen("ODD.txt","w");
while((n=fgetc(fp1))!=EOF)
{
if(n%2==0)
fputc(n,fp2);
else
fputc(n,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp1=fopen("NUMBER.txt","r");
fp2=fopen("EVEN.txt","r");
fp3=fopen("ODD.txt","r");
printf("The content of number file are: ");
while((n=fgetc(fp1))!=EOF)
printf(" %d",n);
printf("\nThe content of even file are: ");
while((n=fgetc(fp2))!=EOF)
printf(" %d",n);
printf("\nThe content of odd file are: ");
while((n=fgetc(fp3))!=EOF)
printf(" %d",n);
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
The problem I face is that the contents of the files are in hex or binary. I want it to be readable with text editor not a hex editor. The other problem I face is the scanf() doesn't accept 3 digit numbers. The output is given below.
Enter no.of digits: 5
Enter the numbers:
123
34
456
67
789
The content of number file are: 123 34 200 67 21
The content of even file are: 34 200
The content of odd file are: 123 67 21
I tried to write the following code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2,*fp3;
int size,n,a,b;
printf("Enter the size: ");
scanf("%d",&size);
fp1=fopen("numbers1.txt","w");
fp2=fopen("even1.txt","w");
fp3=fopen("odd1.txt","w");
printf("Enter the integers: ");
for(int i=0;i<size;i++)
{
scanf(" %d",&n);
//putc(n,fp1); reads as 12, 234 etc but digits in file is not visible
fprintf(fp1," %d\n",n);//reads 12, 234 as 12234 but digits in file are visible
}
fclose(fp1);
fp1=fopen("numbers1.txt","r");
n=getc(fp1);
while(n!=EOF)
{
if(n%2==0)
putc(n,fp2);
else if(n%2==1)
putc(n,fp3);
n=getc(fp1);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
In the above code the content in the files are in text, but the odd and even files read char by char. The contents of odd, even and number files are given blow.
odd file:
133577
even file:
2
4
46
6
8
Number file:
123
34
456
67
78
Please help me
It is almost always a bad idea to require the number of data points to be specified before the data is given. Generally, the only reason to do that is to simplify the code so that you don't need to grow data structures. In this case, however, you are writing all the data to a file so you don't even need to do that, since the file provides the storage for you.
To write human readable integers, you need to format the data. The most common way to do that is with printf. There are a lot of ways to do what you're asking, and this is just one idea:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
struct named_file {
const char *name;
FILE *fp;
};
void xfopen(struct named_file *f, const char *mode);
void xfclose(struct named_file *f);
void display(const struct named_file *f);
int
main(void)
{
struct named_file f[3];
int n;
f[0].name = "NUMBER.txt";
f[1].name = "EVEN.txt";
f[2].name = "ODD.txt";
xfopen(f, "w");
while( scanf("%d", &n) == 1 ){
fprintf(f[0].fp, "%d\n", n);
}
xfclose(f);
xfopen(f + 0, "r");
xfopen(f + 1, "w");
xfopen(f + 2, "w");
while( fscanf(f[0].fp, "%d", &n) == 1 ){
FILE *out = n % 2 ? f[2].fp : f[1].fp;
fprintf(out, "%d\n", n);
}
for( int i = 0; i < 3; i += 1 ){
xfclose(f + i);
xfopen(f + i, "r");
display(f + i);
xfclose(f + i);
}
}
void
xfopen(struct named_file *f, const char *mode)
{
f->fp = fopen(f->name, mode);
if( f->fp == NULL ){
perror(f->name);
exit(EXIT_FAILURE);
}
}
void
xfclose(struct named_file *f)
{
if( fclose(f->fp) ){
perror(f->name);
exit(EXIT_FAILURE);
}
}
void
display(const struct named_file *f)
{
int n;
printf("The contents of %s: ", f->name);
while( fscanf(f->fp, "%d", &n) == 1 ){
printf(" %d",n);
}
putchar('\n');
}

C Programming - Generating Random Numbers into a new text File and retrieving them to count the occurrences (then do statistics on the side)

My goal is to generate random numbers into a new txt file where I can retrieve the randomly generated values and count the occurrences of the values (e.g. Number 1 has appeared "x" number of times). My expected output should display an output like the example given and all the occurrences should add up to 600. There is an underline on the last bracket in my newfile() function. Thanks in advance.
First 10 lines of txt output file...
2
5
4
2
6
2
5
1
4
2
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int newfile(FILE *fp)
{
char fname[20];
printf("\nEnter the name of the file... ");
scanf("%19s",fname);//File name cannot have spaces
strcat(fname, ".txt");
fp=fopen(fname, "w");
int i, N = 600, newfile[N];
for(i=0;i<N;i++)
{
newfile[i]= ((rand() % 6)+1);
fprintf(fp,"%d\n",newfile[i]);
}
}
int main()
{
int i = 0;
FILE *fp;
do
{
newfile(fp);
i++;
}
while (i<1);
FILE* fpointer;
char filename[20];
int value = 0, result = 0, num[600] = { 0 };
float sum, mean;
printf("\nEnter the name of the file... ");
scanf("%19s",filename);
fpointer = fopen(filename, "r");
if (fpointer == NULL) {
printf("ERROR: CANNOT OPEN FILE!\n");
return -1;
}
result = fscanf(fpointer, "%d", &value);
while (result == 1)
{
{
num[value] = num[value] + 1; // num[value]++
}
result = fscanf(fpointer, "%d", &value);
}
for (int i = 0; i <= 6; i++) {
if (num[i] > 0) {
printf("Number %i has appeared %d times\n", i, num[i]);
}
}
sum = (1*(num[1])+2*(num[2])+3*(num[3])+4*(num[4])+5*(num[5])+6*(num[6]));
mean = sum / 600;
printf("\nThe mean is %f",mean);
fclose(fpointer);
return 0;
}
The main problem in your code is that you forgot to close the file inside newfile function.
So just add fclose(fp); at the end of the function.
Minor issues:
you don't need to pass fp to the function newfile. Just use a local variable.
newfile[N] is not needed at all. Simply do: fprintf(fp,"%d\n", (rand() % 6)+1);
num[600] = { 0 }; is much too large as you only use index 0 .. 6
Before doing num[value] = ... you should check that value is in the expected range, i.e. to avoid writing out of bounds.

C programming: Finding max in a file string

I have this assignment that I can't figure out.
We have a file in the following format:
5
4
100 500 250 300
1
700
3
300 150 175
2
920 680
8
20 10 15 25 50 30 19 23
On the first line we have the total number of auctions.
Afterwards, each two rows represent an auction.
On the first row there is the number of bids. On the following row there are the actual bids.
For example the number 4 describes an auction with 4 bids (100,500,250,300).
My task is to determine the highest bid for each auction. This is what I've got so far. Any help will be appreciated.
#include <stdio.h>
int main() {
FILE * ifp;
char filename[100];
printf("File name\n");
scanf("%s", &filename);
ifp = fopen (filename, "r");
if (ifp == NULL) {
printf("Error, File could not be opened.\n");
return 1;
}
int i, num_auctions, auction, j, bid, max;
fscanf(ifp, "%d", &num_auctions);
for(i=0; i<num_auctions; i++) {
fscanf(ifp, "%d", &auction);
if (bid > max)
max = bid;
for(j=0; j<auction; j++){
fscanf(ifp, "%d", &bid);
printf("%d\n", bid);
}
printf("%d\n", max);
}
fclose(ifp);
return 0;
}
These are the problems in your code.
bid and max are used unintialised. Fix is to set them to 0 when they are declared.
The if (bid > max) check is in the wrong spot. It's only checking the last bid of each auction. The fix is to move that check into the inner for loop after the fscanf.
max needs to be cleared after each auction. The fix is to set max to 0 at the top of the outer for loop.

C Program to get file name and range of numbers from user generate numbers from a specified range and print to file

I am writing a program to get a few things from the user and then write the results to a file. The program will get the file name, number of numbers to generate, the lowest and highest numbers to be generate, then write it all to a file that is named by the user.
The program is doing two things that are not correct:
it is generating numbers outside the user specified range
it is adding a ? to the end of the file name, I tried using strlen to remove the last character of the string but I get and error: incompatible implicit declaration of built-in function 'strlen'.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[100];
FILE *fout;
int i, x, len;
int h, l, q, a;
printf("Please enter the file name: ");
fgets(s, sizeof(s), stdin);
printf("How many numbers should we generate: ");
scanf("%d", &q);
printf("lowest number to generate: ");
scanf("%d", &l);
printf("Highest number to generate: ");
scanf("%d", &h);
fout = fopen(s, "wb");
a = h - l;
if ( fout == NULL)
{
printf("That file is not available\n");
exit(1);
}
fprintf(fout, "%d\n", q);
for (i=0; i < q; ++i)
{
x = (rand() % l) + a;
fprintf(fout, "%d ", x);
}
fclose(fout);
return 0;
}
concerning the file name: remove the newline character '\n' (or '\x0a') at the end of s after fgets():
if( s[strlen(s)-1] == '\n' )
s[strlen(s)-1] = '\0';
for completeness: on windows you had to remove carriage return + newline '\r'+'\n' (or '\x0d'+'\x0a')
concerning the wrong numbers: it should be x = (rand() % a) + l; (modulus range + lowest, not the other way round)

Find most frequent string in a binary file C

The purpose of this program is to ask user input for how many exams will be entered into a binary file. When we get user input, e.g. 5, the do while loop asks for input of the name of the course in which the exam was taken and the grade that was received. This gets written in the exams.bin and opened for reading and finding the occurrence of a user inputted keyword for an exam which grade average should be calculated. It finds the grades for that specific course, adds them up and divides them with the number of students that took the exam (the number of recurrence of the name of course). It then prints out a float. And this all works in the code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char courseName[30];
int grade;
} exam;
int main()
{
exam firstExam, secondExam;
int examNumber, i = 1, j = 1, gradeSum = 0, studentNumber = 0, mostFreq = 0;
float gradeAverage;
char subjectName[30];
char mostFrequent[30];
FILE *pointerBinExam = NULL;
char fileName[13] = "exams.bin";
pointerBinExam = fopen(fileName, "w+b");
if(pointerBinExam == NULL)
{
printf("File doesn't exist!");
exit(EXIT_FAILURE);
}
printf("How many exams will you input: ");
scanf("%d", &examNumber);
fflush(stdin);
do{
printf("\nCourse name: ");
fgets(firstExam.courseName, 30, stdin);
printf("\nGrade: ");
scanf("%d", &firstExam.grade);
fwrite(&firstExam, sizeof(exam), 1, pointerBinExam);
fflush(stdin);
i++;
}while(i < examNumber+1);
rewind(pointerBinExam);
printf("\nInput the name of the course you wish to calculate grade average: ");
fgets(subjectName, 30, stdin);
do{
fread(&secondExam, sizeof(exam), 1, pointerBinExam);
if (strncmp(subjectName, secondExam.courseName, 30) == 0){
gradeSum += secondExam.grade;
studentNumber += 1;
}
j++;
}while(j < examNumber+1);
gradeAverage = (float)gradeSum/studentNumber;
printf("\nNumber of students who took the exam: %d\n", studentNumber);
printf("\nGrade average: %f", gradeAverage);
studentNumber = 0;
rewind(pointerBinExam);
strcpy(mostFrequent, secondExam.courseName);
rewind(pointerBinExam);
do{
fread(&secondExam, sizeof(exam), 1, pointerBinExam);
if (strncmp(mostFrequent, secondExam.courseName, 30) == 0){
mostFreq += 1;
studentNumber += 1;
}
j++;
}while(j < examNumber+1);**
fclose(pointerBinExam);
return 0;
}
The last part of the code, the new do while loop is not a good approach for my problem. My goal is to put the pointer at the beginning of the binary file and read it again. It should find the most frequent course name in the binary. How should I go about doing this? Is there a command I'm unaware of, or should this be handled with a 2D array that sorts the strings in the binary. I'm clueless and only beginning to understand binaries, this is a test assignment I need to practice. Any tips would be highly appreciated!
To figure out the most frequent course if the binary file is constructed of records in form of exam you need to read the file from the beginning to the end and then have some kind of counter for each course.
This can be done in many ways, e.g. encode each course name to a unique integer and then count ++1 every time you find the same course in the file or you could have a list of courses encountered then search the list - if you find the same course add to counter or add new node in the list with counter = 1

Resources