Here is the code I have:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,a[40];
char file_name[100];
FILE *file;
printf("enter the file name\n");
scanf("%s",&file_name);
printf("enter the size\n");
scanf("%d",&n);
if((file=fopen(file_name,"rb"))==NULL)
{
printf("cant open a file\n");
return;
}
fread(a,sizeof(int),n,file);
for(i=0;i<n;i++)
{
printf("%s",a[i]);
}
}
Change:
scanf("%s",&file_name);
to:
scanf("%s", file_name);
You also need to change:
printf("%s",a[i]);
to:
printf("%d", a[i]);
(and while you're at it, change void main to int main).
scanf("%s",&file_name);
you don't have to pass a pointer to file_name since it's already a pointer. Change this line to:
scanf("%s", file_name);
Related
This may have some other mistakes. But the only thing I concern is fscanf. It doesn't read new line. It reads only the first line. Can you please tell me how to fix it.
#include <stdio.h>
#include<stdlib.h>
int main(void){
int no = 0;
FILE *cPtr;
cPtr = fopen("number.dat","a");
if(cPtr==NULL){
printf("Unexpected error detected while creating new file\n");
}
do{
printf("Enter your number : ");
scanf("%d",&no);
if(!(no==-99)){
fprintf(cPtr,"%d\n",no);
}
}while(!(no==-99));
fclose(cPtr);
int n,i;
FILE *fp;
fp=fopen("number.dat","r");
if(fp==NULL){
printf("Error");
exit(1);
}
for(i=1;i<10;i++){
fscanf(fp,"%d",&n);
printf("\n%d",n);
fclose(fp);
}
}
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
clrscr();
FILE *fp;
int rno,m;
char name[20];
char ch;
printf("INPUT DATA:\n");
fp=fopen("DATA.txt","w");
if(fp==NULL)
{
printf("\nCan't open file or file doesn't exist");
exit(0);
}
do
{
printf("\nEnter Roll number:");
scanf("%d",&rno);
fprintf(fp,"Roll number=%d",rno);
printf("\nEnter name:");
scanf("%s",name);
fprintf(fp,"Name=%s",name);
printf("\nEnter mark secured:");
scanf("%d",&m);
fprintf(fp,"Mark=%d",m);
fprintf(fp,"%d %s %d",rno,name,m);
printf("\nDo you want to add another data(Y/N):");
ch=getche();
}while(ch=='Y'||ch=='y');
printf("\nData written successfully");
fclose(fp);
printf("\nOUTPUT DATA:\n");
printf("ROLL NUMBER\tNAME\tMARK");
fp=fopen("DATA.txt","r");
if(fp==NULL){
printf("\nCan't open file or file doesn't exist");
exit(0);
}
printf("\nData in file:\n");
while((fscanf(fp,"%d %s %d",&rno,name,&m))!=EOF)
printf("\n%d%s%d",rno,name,m);
getch();
fclose(fp);
}
OUTPUT-
If i enter 2 data for example,then the output is as follows
roll number-1
name-abc
mark-24
Do you want to add another data-Y
roll number-2
name-xyz
mark-25
Do you want to add another data-N
Data written successfully
Data in file-
2xyz25
2xyz25
2xyz25
2xyz25
...........
until break is given.
I have edited my code because of fear that someone from the same course as me would copy my code and hand it in. Thanks for the answer you have given me, its a great help.
My program should allow me to add the new item into the system along with its name, price and quantity.
But during execution, my code seems to damage the file. I have no idea what's wrong and would not like to write a more complicated code.
The program just skip the quantity and return to the menu. Not allowing me to input the quantity .
#include <stdlib.h>
#include <string,h>
struct Item//declaring a structure
{
char code[25];//variables inside a structure
char name[25];
double price;
int quantity;
};
int main (void)
{
struct Item item;
FILE *fgst;
printf("-------------------------------\n");
printf(" ADD PRODUCT\n");
printf("-------------------------------\n");
fgst = fopen("gst.txt", "r");
if(fgst==NULL)
{
printf("File cannot be found\n");
}
else //else statement
{
printf("Add Code:\n");
scanf("%s", item.code);
printf("name:\n");
scanf("%s", item.name);
printf("price:\n");
scanf("%.2f",&item.price);
printf("quantity:\n");
scanf("%d", &item.quantity);
fprintf(fgst,"%s;%s;%.2f;%d\n",item.code,item.name,item.price,item.quantity);
fclose(fgst);
}//end else statement
break;
}
The content of the one of the file is as follow:
AS520;Jelly tartar;5.35;42
From the man scanf:
The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format.
The following statements are wrong:
scanf("%.2f",product.price);
scanf("%d", product.quantity);
They should have had the following form:
scanf("%.2f",&(product.price));
scanf("%d", &(product.quantity));
Your program crashes because of these lines:
scanf("%.2f",product.price);
scanf("%d", product.quantity);
scanf expects a pointer but you provide a double and an integer. Change these lines to:
scanf("%.2f",&product.price);
scanf("%d", &product.quantity);
And it will not crash. Also, you are trying to update a file but you open it as read only:
fopen("gst.txt", "r");
If you want to write to the file, you should use:
fopen("gst.txt", "ra");
I've fixed your segmentation fault and tested your program. Your scanf usage was the source of the problem.
#include <stdlib.h>
#include <stdio.h>
struct Product//declaring a structure
{
char code[25];
//variables inside a structure
char name[25];
double price;
int quantity;
};
int main(void) {
struct Product product;
int add;
FILE *fptr;
FILE *nfptr;
printf("-------------------------------\n");
printf(" ADD ITEM\n");
printf("-------------------------------\n");
printf("1.GST Items\n");
printf("2.Non-GST Items\n");
scanf("%d", &add);
switch (add) //start of switch statement
{
case 1:
fptr = fopen("gst.txt", "wr"); //open file
if (fptr == NULL)//checking whether the file is empty or not
{
printf("File cannot be found\n");
}
else //else statement
{
printf("Add Item Code:\n");
scanf("%s", product.code);
printf("Item name:\n");
scanf("%s", product.name);
printf("Item price:\n");
scanf("%.2lf", &product.price);
printf("Item quantity:\n");
scanf("%d", &product.quantity);
fprintf(fptr, "%s;%s;%.2f;%d\n", product.code, product.name, product.price, product.quantity);
fclose(fptr);
}//end else statement
break;
case 2:
nfptr = fopen("ngst.txt", "r"); //open file
if (nfptr == NULL)//checking whether the file is empty or not
{
printf("File cannot be found\n");
}
else //else statement
{
printf("Add Item Code:\n");
scanf("%s", product.code);
printf("Item name:\n");
scanf("%s", product.name);
printf("Item price:\n");
scanf("%.2lf", &product.price);
printf("Item quantity:\n");
scanf("%d", &product.quantity);
fprintf(nfptr, "%s;%s;%.2f;%d\n", product.code, product.name, product.price, product.quantity);
fclose(nfptr);
}//end else statement
break;
}
}
The main problem with the code is that it opens the file in read mode, and then tries to write to it. To append data to a file, use append mode ("a").
My purpose is to create programme to manage records in files using c. the programme should be able to get info from console, write to a file and then read from it. Struct itself is working fine, but I'm not getting all the values i have written(see output)
and source code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct dob
{
int date;
int month;
int year;
};
struct person
{
int id;
char firstName[20];
char lastName[20];
struct dob date;
char email[20];
int phoneNo;
}new;
void readRecordsFromFile();
void readRecordsFromKeyboard();
int main(int argc, const char * argv[]) {
puts("Hello");
while (1) {
puts("Select option. \n 1. Read records from file. \n 2. Read records from keyboard \n Type any number to exit\n");
int i;
scanf("%d", &i);
switch (i) {
case 1:
readRecordsFromFile();
break;
case 2:
readRecordsFromKeyboard();
break;
default:
return 0;
break;
}
}
return 0;
}
void readRecordsFromFile(){
//struct person new;
char filename[100];
puts("Scpecify the file name to read data");
scanf("%s", filename);
struct person *new=malloc(sizeof(struct person));
FILE * file= fopen(filename, "rb");
if (file != NULL) {
fread(new, sizeof(struct person), 1, file);
fclose(file);
}
printf("\nID: %d\nName: %s\nSurname: %s\nDay of birth:%d\nMonth of birth:%d\nYear of birth:%d\nE-mail: %s\nPhone Number: %d\n",new->id,new->firstName,new->lastName,new->date.date,new->date.month,new->date.year,new->email,new->phoneNo);
}
void readRecordsFromKeyboard(){
struct person *new=malloc(sizeof(struct person));
puts("Enter the info about person");
puts("ID number");
scanf("%d", &new->id);
puts("First Name");
scanf("%19s", new->firstName);
puts("Last name");
scanf("%19s", new->lastName);
puts("Day, month and year of birth.(by numbers, every is new line)");
scanf("%d", &new->date.date);
scanf("%d", &new->date.month);
scanf("%d", &new->date.year);
puts("Email");
scanf("%19s", new->email);
puts("Phone number");
scanf("%d", &new->phoneNo);
puts("Specify the file you want to write yor data");
char filename[100];
scanf("%99s",filename);
FILE *inputf;
inputf = fopen(filename,"wb");
if (inputf == NULL){
printf("Can not open the file.\n");
exit(0);
}else{
if (fwrite(new, sizeof(new), 1, inputf) != 1)
{
fprintf(stderr, "Failed to write to %s\n", filename);
return;
}else{
puts("Data saved\n");
printf("\nID: %d\nName: %s\nSurname: %s\nDay of birth:%d\nMonth of birth:%d\nYear of birth:%d\nE-mail: %s\nPhone Number: %d\n",new->id,new->firstName,new->lastName,new->date.date,new->date.month,new->date.year,new->email,new->phoneNo);
}
}
fclose(inputf);
}
here is your problem
inputf = fopen(filename,"wb");
This command clears file, because it file is opened with "wb".
If you are going to write multiple record in that file in several runs, open it with "wb+". Then use fseek() to go to end of file. after that write your record with fwrite().
In addition for fwrite() you need to use sizeof strusture, not pointer.Means that you need something like this:
if (fwrite(new, sizeof(struct person), 1, inputf) != 1)
{
}
I have following C program:
#include <stdio.h>
int main()
{
char *filename;
FILE *fp1, *fp2;
int i, number;
fp1=fopen("TEST", "w");
for(i=10; i<=100; i+=10)
{
putw(i, fp1);
}
fclose(fp1);
printf("\nInput filename\n");
open_file:
scanf("%s", filename);
if((fp2=fopen(filename, "r"))==NULL)
{
printf("Cannot open the file.\n");
printf("Type file name again.\n");
goto open_file;
}
else
{
for(i=1; i<=20; i++)
{
number=getw(fp2);
if(feof(fp2))
{
printf("\nRan out of data\n");
break;
}
else
{
printf("%d\n", number);
}
}
fclose(fp2);
}
return 0;
}
I inputed TEST for scanf("%s", filename);. But this statement if((fp2=fopen(filename, "r"))==NULL) is always executing and my compiler is printing Cannot open the file Type file name again randomly. Here is a goto statement. So it should wait for another input. But it is not. Where is the problem??
char *filename; is a pointer and no memory is allocated for it.
Try
char filename[100]; and give valid file name to work.
Problem is scanf("%s", filename); .
As filename is char pointer which is not allocated in your program (this non allocated pointer leads to undefined behavior). So you can either allocated pointer or use char array.
From here scanf, when you write scanf("%s", filename);, means you want to read an string and store the sting into filename, so the filename must be a arry(you should allocate memory for storing the string), but in you code you just write char *filename;, you don't allocate memory.