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);
}
}
Related
Here I am writing some data to a file and trying to display that data.Is it compulsory to use fscanf before printing that data on the output screen? When I use the fscanf and suppose I enter the details as:
Ram
usa
12
the output comes as
Ramusa1212
What might be the possible error here?
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
FILE *fptr;
char name[20],address[20];
int roll;
fptr=fopen("1.txt","w");
if(fptr!=NULL){
printf("file created successfully:you can write into the file now");
}
else{
printf("error creating file");
exit -1;
}
printf("enter your name,address,roll number");
fgets(name,20,stdin);
scanf("%s",address);
scanf("%d",&roll);
fprintf(fptr,"%s%s%d",name,address,roll);
fclose(fptr);
fptr=fopen("1.txt","r");
fscanf(fptr,"%s%s%d",name,address,&roll);
printf("%s%s%d",name,address,roll);
fclose(fptr);
getch();
}
I am a complete beginner of C. My problem is to modify a content in a file.
I am writing two files and then merge the contents of the two files in a another file. This another file is the one I need to modify.
what to modify?
The myfile1.txt values are 199112345671273 and the myfile2.txt values are 24AUS2024MED712.
The merging file (myfile3.txt) has 19911234567127324AUS2024MED712
The thing that I need to modify is the values of myfile2.txt. I want to hide its values in asterisk so when reading myfile3.txt,I get the following
199112345671273****************
my logic is messed up. I just want to stores both values of myfile1 and myfile2. then display myfile3 in condition that myfile2 has to be hidden in asterisk when reading.
My write.c program - write data in two files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
int main (int argc, char **argv) {
char registration[MAX_SIZE], location[MAX_SIZE], faculty[MAX_SIZE];
int birthOfYear, birthOfMonth, birthOfDate, layerArch1, layerArch2, levelOfStudy, graduatingYear;
FILE *fptr, *anotherfptr;
fptr = fopen("myfile01.txt","w");
anotherfptr = fopen("myfile02.txt", "w");
if(fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a registration number (XXXXXX): ");
scanf("%s", registration); //read as a string
printf("Enter location (location as in currency, AUS CND SIN: ");
scanf("%s", location); //read as a string
printf("Enter faculty (ENG BUS SCI MED): ");
scanf("%s", faculty); //read as a string
printf("Enter birth of year (19XX 200X): ");
scanf("%d", &birthOfYear);
printf("Enter birth of month (XX): ");
scanf("%d", &birthOfMonth);
printf("Enter birth of date (XX): ");
scanf("%d", &birthOfDate);
printf("Enter level of study (1 -first, 2- second, 3- third, 4-fourth, 5 - other): ");
scanf("%d", &levelOfStudy);
printf("Enter graduating year (XXXX): ");
scanf("%d",&graduatingYear);
printf("Enter layer of Architecture 1 (0-sensing, 1-network, 2-smart(hidden), 3-devices): ");
scanf("%d",&layerArch1);
printf("Enter layer of Architecture 2 (0-sensing, 1-network, 2-smart(hidden), 3-devices): ");
scanf("%d",&layerArch2);
fprintf(fptr,"%d%s%d%d%d", birthOfYear, registration, birthOfMonth, birthOfDate, layerArch1); //writing into file with some formatting
fclose(fptr);
fprintf(anotherfptr,"%d%d%s%d%s%d%d", layerArch2, levelOfStudy, location, graduatingYear, faculty, birthOfDate, birthOfMonth);
//writing into file with some formatting
fclose(anotherfptr);
return 0;
}
my merge.c program - to merge two files
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *fs1, *fs2, *ft;
char ch, file1[200], file2[200], file3[200];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);
printf("Enter name of file which will store contents of the two files\n");
gets(file3);
fs1 = fopen(file1, "r");
fs2 = fopen(file2, "r");
if(fs1 == NULL || fs2 == NULL)
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
ft = fopen(file3, "w"); // Opening in write mode
if(ft == NULL)
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fs1)) != EOF)
fputc(ch,ft);
while((ch = fgetc(fs2)) != EOF)
fputc(ch,ft);
printf("The two files were merged into %s file successfully.\n", file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}
my read.c - to read files
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char c[1000];
FILE *fptr, anotherfptr;
if ((fptr = fopen("myfile1.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
if ((fptr = fopen("myfile2.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
// reads text until newline
fscanf(anotherfptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(anotherfptr);
return 0;
}
My issue is my logic on how to solve this simple program. I am literally stuck.
Any help/clarification would be much appreciated.
In this case you need to create a program which should know the content/size of 'myfile1.txt' or 'myfile2.txt' so as to show * for the second content while reading 'myfile3.txt'.
I prefer not to create separate c programs for each task but to use it as a function in one single program.
Coming to the logic : Masking is what you are searching for. Basically it is used as a password masking. ( You might have seen * while typing password in any sites. ). In your case you want to display a content as * without actually changing the content in file.
Get an idea of how masking is done for password in the below document :
https://www.geeksforgeeks.org/print-in-place-of-characters-for-reading-passwords-in-c/
Hope you have tried all possible way out. Please check the solution below :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char c1[1000];
char c3[1000];
FILE *fptr, *anotherfptr;
if ((fptr = fopen("myfile1.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c1);
printf("Data from the file myfile1.txt :%s\n", c1);
fclose(fptr);
//calculate the length of string c1
int lengthc1=strlen(c1);
printf("Length of string c1 is : %d\n", lengthc1);
if ((anotherfptr = fopen("myfile3.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
// reads text until newline
fscanf(anotherfptr,"%[^\n]", c3);
printf("Data from the file myfile3.txt :%s\n", c3);
fclose(anotherfptr);
//to show data of myfile2.txt in astrisk
int lengthc3=strlen(c3);
printf("Final data is ");
for ( int i=0 ; i<=lengthc3 ; i++)
{
if (i < lengthc1)
{
printf("%c", c3[i]);
}
else
{
printf("*");
}
}
return 0;
}
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'm having a little trouble with the code below and I can not for the life of me figure out what went wrong and why it is displaying what it does, any help or assistance would be most appreciated. It is supposed to allow 5 lines of text to be entered and display those 5 lines onscreen, however it only allows 4 lines to be entered, and 4 are displayed. Please help!
#include <stdio.h>
int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
scanf("%s",filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
printf("unable to open File");
}
for(n=1;n<6;n++)
{
printf("\nEnter line %d:",n+1);
gets(string);
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
printf("unable to open File");
}
for(n=1;n<6;n++)
{
fgets(string,100,fp);
printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}
The problem is that scanf("%s", filename); doesn't consume the newline after the filename. So your first call to gets() reads this newline as an empty line.
Add:
gets(string);
after that line to use up the rest of the line before you start reading input lines.
Here is the modified code. Added gets instead of scanf and added return 0; if file is not opened.
#include <stdio.h>
int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
gets(filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
printf("\nEnter line %d:",n);
gets(string);
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
printf("unable to open File");
return 0; // do not proceed
}
for(n=1;n<6;n++)
{
fgets(string,100,fp);
printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}
replace scanf("%s",filename) with gets(filename)
To get rid of the newline in the buffer right after your call to scanf, you can simply add getchar();:
scanf("%s", filename);
getchar();
But do adjust your for loops to start at 0, since you add 1 to n i.e:
for(n=0;n<6;n++)
^
After making those changes I was able to input 6 lines and then print all of them out.
As you've noticed, buffered input can be pesky if you don't deal with it properly as it can be inserted in your subsequent input calls. Don't be tempted to flush the stdin.
Here are some recommended alternatives on how to deal with this.
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);