I am getting an error Abnormal program termination when I execute this code.
The objective the program is read array of numbers from file list.txt and perform recursive binary and recursive linear search on that loaded array.
Here is my code:
#include <stdio.h>
#include <conio.h>
void menu();
int a[30000],n;
void main()
{
FILE *fp;
int i, ch;
fp = fopen("list.txt", "r");
if(fp == NULL)
{
printf("\nCant read\n");
exit(0);
}
for(i = 0; i < n; i++)
fscanf(fp, "%d", &a[i]);
fclose(fp);
for(i = 0; i < n; i++)
printf(" %d ", a[i]);
menu();
scanf("%d", &ch);
if(ch == 1)
{
printf("ch1\n");
}
else if(ch == 2)
{
printf("ch2\n");
}
else
{
exit(1);
}
}//end main
void menu()
{
printf("\nEnter the number of elements in array\n");
scanf("%d", &n);
printf("\n1.Linear Search\n2.Binary Search\n3.Exit\nEnter your choice\n");
}
I have the logic for my choice 1 and 2. I need to know whats wrong with my above code. Please help me out in this
Turbo C! That brings back some memories, but I don’t have my copy any more. Anyway, you’re using n before you initialize it in menu(). (As the commenters pointed out.) You might also consider allocating your array with malloc() instead of a fixed size.
Borland Turbo C came with Turbo Debugger, and in fact I think Borland gave it away for free for a while, so running in that can give you an idea where the abnormal termination happened and a stack trace you can use to check the variables that caused it. Another good practice is to put in assert() calls to make sure your assumptions about what’s in your variables are true.
Related
I'm new to c programming. I'd like to use a function inside a switch or if else statement. But after I run the program. It immediately show me segmentation fault and exit the program. Below is my code. Please run through it
void phone1();
int main()
{
int option;
while (1) {
printf("1) Option 1 \n");
printf("2) Option 2 \n");
scanf("%d", &option);
switch (option) {
case 1:
phone1();
break;
case2:
phone2();
break;
default:
printf("Error");
break;
}
while (1);
return 0;
}
}
void phone1()
{
FILE* fi;
char value[100];
fi = fopen("phone.txt", "r");
fseek(fi, -10, SEEK_END);
fgets(value, 100, fi);
printf("%s", value);
fclose(fi);
}
And here is my phone.txt file
phone1 John 192901
phone2 Joseph 858201
phone3 Jay 757279
phone4 Teddy 847291
phone5 Ed 469274
I tried the function outside switch statement inside int main() and everything works fine. So I don't know what cause the segmentation fault to fail within the switch statement.
First of all, you need to add a closing brace for the while loop block and to omit the one in the end.
Second, you shouldn't fseek() to a negative. What did you try to achieve?
Your function opens a file, and reads the first 100 characters into value. Then, it prints them. I think i get what you are trying to achieve here, so this is an example of roughly how I'd do it.
#include <stdio.h>
int main()
{
FILE *fptr = fopen("contacts.txt", "r");
int contact;
char name[100]; // or whatever size you need
int number;
char c = 'a';
scanf("%d", &contact);
++contact; // to use 1-based numbering
for (int i = 0; i < contact && c != EOF; ++i)
while ((c = fgetc(fptr)) != EOF && c != '\n');
// safely jumps to contact-th line
fscanf(fptr, "%s %d", name, &number);
printf("%s\t%d\n", name, number);
return 0;
}
Which would need a contacts.txt in the form:
Ed 1234
Emma 7890
You could also make it check how many contact entries/lines are there, and bound-check the input.
First poster here, and forgive me for the basic ask, but I cannot seem to get my head around as to why this code won't work.
I'm trying to take to input from command line, and perform a simple calculation, however, when I debug the code, the error message that I created from the if statement shows, and not the result of the calculation.
Here's the code that I have made;
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int num1 = 0;
int num2 = 0;
int sum = 0;
int errors = 0;
int read = 0;
if (argc != 3){
errors++;
printf("Error: Less/more than 2 numbers entered.");
}
if (argc == 3){
read = sscanf(argv[1], "%d", &num1);
read = sscanf(argv[2], "%d", &num2);
if (read ==2){
sum = num1 + num2;
printf("%d", sum);
}
else{
printf("something weird happened...");
}
}
}
The values i have in command input is "4" and "3" (without the quotes and a space to separate them). So, the output should be the sum, which would be 7. But I just get the error message "Something weird happened...", which is obviously what I put into the if statement if the above failed.
My guess is it's something to do with my method of using the sscanf() twice? Forgive me, I'm a student learning this stuff for the first time. I have tried reading the book on C and have my lecturers code, but I think I learn better by trial and error, and seeing how it's supposed to work. Any help or guidance would be much appreciated.
What I want to do is to write n(taken from user) elements to a file.Then read the elements again to an array and sort them and again write them in another file.
Finally open that file and display its contents.
But the code seems not to work, all syntax, grammar etc is checked what's the error??
#include<stdio.h>
struct data
{
int a,ar[100];
}e;
int main()
{ FILE *f1,*f2;
int i,j,n,t;
printf("\nEnter Array Size:");
scanf("%d",&n);
f1=fopen("Array.txt","w");
for(i=0;i<n;i++)
{ printf("\nEnter %d element:",i+1);
scanf("%d",&e.a);
fprintf(f1,"%d",e.a);
}
fflush(stdin);
fclose(f1);
rewind(f1);
i=0;
f1=fopen("Array.txt","r");
while((fscanf(f1,"%d",&e.ar[i++]))!=EOF)
{}
fclose(f1);
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)
{ if(e.ar[j]>e.ar[j+1])
{ t=e.ar[j];
e.ar[j]=e.ar[j+1];
e.ar[j+1]=t;
}
}
}
f2=fopen("Sort.txt","w");
i=0;
while((fprintf(f2,"%d",e.ar[i]))!=EOF)
{ i++;}
fclose(f2);
f2=fopen("Sort.txt","r");
while((fscanf(f2,"%d",&e.a))!=EOF)
{ printf("%d ",e.a);
}
fclose(f2);
return 0;
}
So you want to know the error? I found a HUGE one.
As I was running your program, I have determined a segmentation fault occurs after this line:
f2=fopen("Sort.txt","w");
The major error here is that you opened a file for writing data to it, but you're making a rather confusing loop.
This is your code:
i=0;
while((fprintf(f2,"%d",e.ar[i]))!=EOF)
{ i++;}
In the state it is in, the value of i will exceed the upper bound value of your ar int array. You set the upper bound value to 100, but in the while loop, it will run endlessly until segmentation fault happens (when i goes past 100) because fprintf will never return an EOF (according to what the linux manual on fprintf claims).
What I would suggest instead is this:
for(i=0;i<n;i++){
fprintf(f2,"%d",e.ar[i]);
}
where n is the number of elements to finally print (as indicated by user at beginning of the program).
I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)
I need to have a user input a word then compare the word with a text file to see if it is correct. The user has 3 attempts to enter the word before the program terminates. My issue is reading the word from the file I know it's something simple that I have wrong. I should also clarify that the error I'm getting is in the compiler I haven't gotten to the point of being able to compare the strings yet!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("secret.txt","r");
char guess[10];
const char secret[10];
int i, c;
c = getc(fp);
fgets(secret, sizeof(secret), fp);
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
while (c !=EOF)
{
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct");
return 0;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
fclose (fp);
}
return 0;
}
Here are some pointers:
c = getc(fp) consumes the first character of the file, so it never becomes part of the secret variable.
If secret.txt contains a newline, the newline is read into the secret variable.
The while (c != EOF) loop seems pointless, since c isn't modified inside the loop. Furthermore, the infinite nature of the loop prevents the outer for loop from functioning correctly.
If I were you, I'd fix the while loop and would make sure that secret is read correctly, for example by printing it out or examining it in a debugger.
What is
c = getc(fp);
needed for? My "guess" would be that you read the first character of the word into c and then secret misses the first character.
EDIT: Instead of using getc for EOF checking, which as said corrupts the read word (and this while loop is rubbish anyway), just check the return value of fgets:
if(fgets(secret, sizeof(secret), fp) == NULL)
//file is empty or other error occurred
and remove this infinite while(c != EOF) loop.
So it should rather look something like:
FILE *fp = fopen("secret.txt","r");
char guess[10];
const char secret[10];
int i;
if(fgets(secret, sizeof(secret), fp) == NULL)
{
printf("Error while reading file\n");
return -1;
}
fclose(fp);
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess) == 0)
{
printf("Your guess was correct");
return 0;
}
else
printf("Your guess was incorrect. Please try again\n");
}
return 0;
Your code is grossly off: you do not alter 'c' inside a loop, making it spin indefinitely. It's a good idea to sketch your algorithm on a piece of paper before you start coding. In your case, pseudocode should look like this:
Open file
Read the secret
Close file
Repeat three times:
--- Display the prompt
--- Read user input
--- If user input matches the secret, congratulate the user and exit.
Tell the user his guess was incorrect.
At this point, converting it to C should be more or less mechanical. Good luck!
while (c !=EOF)
{
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct");
return 0;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
looks like an infinite loop to me