Program to take integer input from user and store them in a file, then sort the integers into two different files (odd and even), when I used fprintf it overwrites the previous value thats why I tried putw() but I am getting gibberish values in files
This is my code:
#include<stdio.h>
int main()
{
int n,a[50];
printf("\nEnter no of entries:");
scanf("%d",&n);
FILE *f1,*f2,*f3;
f1=fopen("Numbers.txt","w+");
for(int i=0;i<n;i++)
{
printf("\nEnter a number:");
scanf("%d",&a[i]);
putw(a[i],f1);
}
fclose(f1);
f1=fopen("Numbers.txt","r");
for(int i=0;i<n;i++)
{
if(a[i]%2==0)
{
f2=fopen("EvenNum.txt","w+");
putw(a[i],f2);
fclose(f2);
}
else
{
f3=fopen("OddNum.txt","w+");
putw(a[i],f3);
fclose(f2);
}
}
}
That's not what putw does. putw writes an int in binary not as text. Do you mean fprintf(f1, "%d", a[i]);?
The man page for getw and putw says to use fread and fwrite instead, which doesn't seem to fit here.
f1=fopen("Numbers.txt","w+"); will clobber the file. Do you want "a+" to append?
I am making a program that saves information about vehicles in an array made of structs and then prints it to a file. Included in the program are options to add and delete vehicles as well as printing out the saved vehicles and deleting vehicles. When choosing a vehicle to delete or print out I have to make sure the input from the user is an integer to prevent it from crashing, and if it is not an integer to give a custom error message and give the user another chance at the input. I have tried a couple of different approaches and the latest seemed promising but when running these functions I get "Segmentation fault: 11" regardless of if I input an integer or a character.
The functions seem to work just fine without the lines of code that are supposed to prevent crashing. Could someone please tell me what is causing the error or possible fixes to the problem. Thanks!
These are the functions that are causing the problem:
Function to remove vehicle:
This function takes in the array of structs as well as the int counter which counts the number of occupied spots in the array. The function then takes input from the user in the form of an int to choose which position to delete. The position can't be greater than counter or smaller than 0.
//Ta bort ett fordon
void del(int counter, fordon_t reg[])
{
int pos;
int i;
do{
printf("Vilken position ska tas bort?:");
char *tmp;
scanf("%s", tmp);
pos = atoi(tmp);
if (pos == 0)
{
printf("Var god och skriv en siffra\n");
}
}
while(pos == 0);
if(pos<0 || pos>=counter)
{
printf("Ogiltig position\n");
}
else
{
for(i=pos+1; i<counter; i++)
{
reg[i-1]=reg[i];
}
counter--;
for(i=0; i<counter; i++)
{
printf("%s %d %s %s %s\n", reg[i].owner.name, reg[i].owner.age, reg[i].type, reg[i].brand, reg[i].regnum);
}
}
}
Function to print out chosen vehicle:
This function works in the same way as the previous function but instead of deleting the chosen position it prints out the information on that position.
//Skriv ut specifikt fordon
void print_out(int counter, fordon_t reg[])
{
int val;
do
{
char *tmp;
printf("Vilken postition vill du se?:");
scanf("%s", tmp);
val = atoi(tmp);
if (val == 0)
{
printf("Var god och skriv en siffra\n");
}
}
while(val == 0);
if(val<0 || val>=counter)
{
printf("Ogiltig position\n");
}
else
{
printf("%s %d %s %s %s\n", reg[val].owner.name, reg[val].owner.age, reg[val].type, reg[val].brand, reg[val].regnum);
}
}
If additional information about my program is needed to solve the program please tell me and I will provide more of the code.
I'm trying to ensure that the user has definitely entered an integer. However no matter what I type in, it doesn't seem to work.
Sometimes the scanf is completely ignored and the loop just prints out everything loads of times.
When I checked what the input was that the code took in, it was wrong as well.
Any ideas or help would be appreciated!
while (square_size == -1) {
square_size = get_input_size();
}
int get_input_size(void) {
int size;
printf("What size word square would you like to create? ");
scanf("%d", &size);
if (isdigit(size)) {
printf("VALID %d\n", size);
return size;
}
printf("ERROR: invalid input\n");
return -1;
}
I'm trying to make a program that can store certain information in a text file. The problem I have though is that with the code I've written so far, the information stored is a bunch of weird symbols and characters. I've managed to kind of find out where it happens from but I can't seem to solve it. It seems like in my register_item function, both item number and balance get weird values for some reason. If anyone can see what mistake I've made, that would be appreciated.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 20
struct vara
{
int itemnumber[20];
char name[30];
int balance[20];
};
open_file(FILE *ange_filnamn, char filnamn[], struct vara varor[], int *antal_varor)
{
int mainmenu = 0;
while (mainmenu != 1 && mainmenu != 2)
{
printf("Do you want to open an existing file (1) or create a new one (2)?\n");
scanf("%d", &mainmenu);
//system("CLS");
if(mainmenu==1)
{
printf("Choose filename (ex. .txt).\n");
scanf("%s", filnamn);
ange_filnamn=fopen(filnamn, "r+");
while(!feof(ange_filnamn))
{
fread(&varor[*antal_varor], sizeof(struct vara), 1, ange_filnamn);
if(!feof(ange_filnamn))
{
*antal_varor=*antal_varor + 1;
}
}
printf("\nNumber of items: %d \n",*antal_varor);
fclose(ange_filnamn);
}
if(mainmenu==2)
{
printf("What name do you want for your new file?\n");
scanf("%s", filnamn);
ange_filnamn=fopen(filnamn, "w+");
printf("File is created!\n");
*antal_varor = 0;
fclose(ange_filnamn);
}
}
}
register_item(struct vara *varor, int *antal_varor)
{
printf("Item number:\n");
scanf("%d", varor[*antal_varor].itemnumber);
printf("Name:\n");
scanf("%s", varor[*antal_varor].name);
printf("Balance:\n");
scanf("%d", varor[*antal_varor].balance);
*antal_varor+=1;
}
print_item(struct vara varor[], int antal_varor)
{
int i;
for (i=0; i < antal_varor; i++)
{
printf("%d. Item number: %d Name: %s Balance: %d\n", i, varor[i].itemnumber, varor[i].name, varor[i].balance);
}
}
quit_program(char filnamn[], struct vara varor[], int *antal_varor)
{
FILE *fil;
//printf("%s", filnamn);
fil=fopen(filnamn, "w+");
fwrite(varor, sizeof(struct vara), *antal_varor, fil);
fclose(fil);
}
int main(void)
{
FILE *ange_filnamn;
struct vara varor[MAX];
int mainmenu, menu, antal_varor=0;
char filnamn[20], filen[30];
open_file(ange_filnamn,filnamn, varor, &antal_varor);
//Second menu
while(menu!=7)
{
printf("\n");
printf("1. Register new items to inventory.\n");
printf("2. Print all items from inventory.\n");
printf("3. Search for item.\n");
printf("4. Change inventory.\n");
printf("5. Sort inventory.\n");
printf("6. Deregister item from inventory.\n");
printf("7. Quit.\n");
scanf("%d", &menu);
if(menu==1)
{
register_item(varor, &antal_varor);
}
if (menu==2)
{
print_item(varor, antal_varor);
}
if (menu==3)
{
printf("test");
}
if (menu==4)
{
printf("test");
}
if (menu==5)
{
printf("test");
}
if(menu==6)
{
printf("test");
}
if (menu==7)
{
quit_program(filnamn, varor, &antal_varor);
}
}
}
You have an array of structures. The array contains antal_varor number of structures, and each structure contains members (elements) itemnumber, name, and balance.
Before we get started, a little side note: I think your structure definition has some bugs. Based on the way you're using it, I think you want
struct vara
{
int itemnumber;
char name[30];
int balance;
};
But your question was about writing the file out. When you call
fwrite(varor, sizeof(struct vara), *antal_varor, fil);
you are writing out the entire array, all at once, in "binary", which is why you can't read it. If you want to write it out in a more human-readable form, you can do something like this. Here I have an explicit loop over the elements of the array, and each time through the loop, I print out all the members of that element:
int i;
for(i = 0; i < *antal_varor; i++ {
fprintf(fil, "varor %d:\n", i);
fprintf(fil, " itemnumber: %d\n", varor[i].itemnumber);
fprintf(fil, " name: %s\n", varor[i].name);
fprintf(fil, " balance: %d\n", varor[i].balance);
}
So, first try that. You should find that the output file is perfectly readable.
Now, the problem is that since you wrote the file out in this nicer, more readable format, your code that reads the data back in, that used to use
fread(&varor[*antal_varor], sizeof(struct vara), 1, ange_filnamn);
is not going to work any more. But here is the sort of code you could use to read the new-format file back in. This code reads the file line by line with fgets, figuring out what each line is, and plugging data items one by one into the varor array to rebuild it.
char line[80];
int i = 0;
*antal_varor = 0;
while(fgets(line, sizeof(line), ange_filnamn) != NULL) {
if(strncmp(line, "varor ", 6) == 0) {
sscanf(line, "varor %d:", &i);
if(i >= MAX) {
fprintf(stderr, "warning: index in file too large\n");
i = 0;
continue;
}
if(i + 1 > *antal_varor) *antal_varor = i + 1;
} else if(strncmp(line, " itemnumber:", 12) == 0) {
sscanf(line, " itemnumber: %d", &varor[i].itemnumber);
} else if(strncmp(line, " name:", 6) == 0) {
sscanf(line, " name: %s", varor[i].name);
} else if(strncmp(line, " balance:", 9) == 0) {
sscanf(line, " balance: %d", &varor[i].balance);
} else {
fprintf(stderr, "warning: unrecognized line in file\n");
}
}
printf("\nNumber of items: %d \n",*antal_varor);
fclose(ange_filnamn);
I haven't tested this, so there may be some little mistakes in it, but it should give you the idea.
(Also there are better ways of writing this sort of thing, but they're a little more elaborate or require more infrastructure, so I've stuck to something very simple and understandable, although it's less than robust.)
The commenters on your question have it right.
- What is displayed with printf (and written to a file with fprintf) is ASCII representation of the numbers.
- What is stored in memory (and written with fwrite) is the actual "binary" value.
In C, an int variable always takes up the same number of bytes in memory, regardless of the value stored. That is why your sizeof() works consistently. Reading and writing can be consistently done.
(Note that not all C implementations use the same size int though. It is 4 bytes in the x86 Linux I'm using right now).
When displaying the ASCII representation, the number of ASCII digit characters required depends on the value. So, if reading values in that have been stored this way, you have to 'parse' the text and build up the integer value from the digits read, and in general will be a variable number of digits. (This is what scanf does.) Hence, reading and parsing ASCII could be considered more complicated than just reading in a value stored as binary int that is always the same size.
IMPORTANT: If you are going to read the file as binary, you should open it with the "b" attribute like this:
ange_filnamn=fopen(filnamn, "r+b");
Similary, to open for binary write:
fil=fopen(filnamn, "w+b");
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.