I'm trying to figure out how to work out the selection for when the input information is not present in the text file, the user will be notified. For now when I run my code and input an item that's not in the text file, it just print out the last item in the text file. I'm really stuck after several hours of thinking how to solve this problem. Your help is greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
int main()
{
FILE *items;
char pName[20];
float pPrice;
char p1Name[20];
int found=0, i=9;
char respond='y';
items=fopen("Product_Name_Price.txt", "r");
if(items==NULL)
{
fprintf(stderr, "Can't open file Product_Name_Price.txt!\n");
exit(1);
}
printf("File has been successfully opened\n");
while(tolower(respond) == 'y')
{
items=fopen("Product_Name_Price.txt", "r");
printf("Enter the name of the product you are looking for\n");
scanf("%s", p1Name);
while(!feof(items))
{
fscanf(items, "%s%f", pName, &pPrice);
i=strcmp(p1Name, pName);
if(i == 0)
{
found=1;
break;
}
else
{
found=0;
}
}
if(found=1)
{
printf("%s\t%.2f\n", pName, pPrice);
}
else
{
printf("No such product information in the database\n");
}
printf("Do you want to look for more item? (Y/N)\n");
scanf(" %c", &respond);
fclose(items);
}
}
if(found=1) should be if(found == 1)
Related
Hi I have trying to merge two text files alternatively in a way that I get one line from first file and then I get second line from the next one, please help me, spent way too much time on this and still cannot get anything on the new file. Code is given below.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *pointer1, *pointer2, *pointer3;
char source1[80],source2[80],target[80];
char ch1,ch2;
printf("Enter the source and source 2\n");
scanf("%s %s", source1,source2);
printf("Enter the destination\n");
scanf("%s",target);
pointer1 = fopen(source1,"r");
pointer2 = fopen(source2,"r");
pointer3 = fopen(target,"w");
if(pointer1 == NULL || pointer2==NULL || pointer3==NULL)
{
printf("Cannot open a file\n ");
exit(1);
}
while(1)
{
if(ch1!=EOF)
{
ch1 = fgetc(pointer1);
while(ch1!='\n')
{
if(ch1==EOF)
break;
fputc(ch1,pointer3);
ch1=fgetc(pointer1);
}
}
if(ch2!=EOF)
{
ch2=fgetc(pointer2);
while(ch2!='\n')
{
if(ch2==EOF)
break;
fputc(ch2,pointer3);
ch2=fgetc(pointer2);
}
}
if(ch1==EOF && ch2==EOF)
break;
}
printf("Merging completed successfully\n");
printf("Press any key to exit\n");
getch();
}
I can't get my delete record function to break out of the switch case or even give me an error when the record doesn't exist. Could someone please tell me why this is?
Any help is much appreciated!
I can't get my delete record function to break out of the switch case or even give me an error when the record doesn't exist. Could someone please tell me why this is?
Any help is much appreciated!
void delete_record();
void displayContent();
struct Update
{
char studentName[50];
char studentID [50];
char emailID[100];
char courseID[5];
char grade[50];
} update2;
int main ()
{
int num;
do
{
printf("1. Delete a record for the specific name\n");
printf("2. Display Content of File\n");
printf("6. Exit\n");
switch(num)
{
case 1:
printf("this is a test\n");
delete_record();
break;
//displayContent();
//printf("this is a test 2\n");
case 2:
printf("\n\nDiplaying Contents of File\n\n");
displayContent();
default:
printf("Give me a break!\n");
break;
}
scanf("%d", &num);
} while (num != 6);
return 0;
}
void delete_record()
{
FILE *fp;
FILE *fp_tmp;
fp = fopen ("BINARY_FILE.txt", "w");
char studentsID[20];
printf("enter studentID to delete:");
scanf("%s",studentsID);
printf("is this a test?\n");
while(fread(&update2,sizeof(update2),1,fp))
{
printf("this is another test\n");
if(strcmp(update2.studentID,studentsID) != 0)
{
//printf("testing\n");
fwrite(&update2,sizeof(update2),1,fp);
}
else
{
printf("No student with that student ID\n");
}
}
printf("more tests\n");
fclose(fp);
return;
}
void displayContent()
{
char c;
// Open file
FILE *fp;
fp = fopen ("BINARY_FILE.txt", "r");
if (fp == NULL)
{
printf("File Has No Content\n");
exit(0);
}
// Read contents from file
c = fgetc(fp);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fp);
}
fclose(fp);
//return 0;
}
When using scanf to read from the keyboard you must remember
that all characters that you enter are written to the in-buffer,
this means that if you type in
42ENTER
The ENTER will also be present in the in-buffer, so next time you call scanf ENTER will still be in the buffer and then scanf returns 0 since the format specificier "%d" doesn't match.
The easiest way to handle input from keyboard in C and to avoid the hassle of scanf in-buffer by using fgets() to read from the keyboard, then use sscanf() to cherry pick from the buffer:
// always check return value from all runtime functions when possible
char buffer[128];
if (fgets(buffer,sizeof(buffer), stdin) != NULL)
{
if (sscanf(buffer, "%d", &num) == 1)
{
}
else {...}
}
else {...}
I have this code which I divided in two parts just for understanding purpose. The first option is working fine and showing me details to update.
I have a problem with the second part in which a code is taking name/word from the file correctly but I don't know how to replace it with the new name/word in another file? Could you help me with some code because I searched a lot? Thanks!
Here is file.txt
bilalkhan 20/20/1980 908732343
Here is a code
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void firstWord(char str[]){
int i = 0;
while(!isspace(str[i])){
i++;
}
str[i]='\0';
}
void hello(){
int option;
char updated_name[50], read[100];
short int FLAG = 0;
static const char * listing[] = {"Name", "Date of birth","ID card number"};
FILE * fr3 = fopen("file.txt","r");
FILE * fw1 = fopen("new.txt","w");
if (fr3 == NULL || fw1 == NULL) {
perror("Unable to read text file.");
exit(0);
}
for (option = 1; option <= sizeof(listing)/sizeof(char *); ++option)
printf("%d. Your %s\n", option, listing[option-1]);
SELECT OPTION TO UPDATE
fputs("Select your choice to update: ", stdout);
scanf("%d", &option);
char string[100];
if (option == 1){
while(fgets(string, 100, fr3) != NULL){
firstWord(string);
printf("'%s' found. Now replace it with another name: ", string);
scanf("%s", &updated_name);
// Here I want to update the name but don't know the code.
fclose(fr3);
exit(0);
}
}
fclose(fw1);
}
int main(){ hello(); }
Just write the updated name to the output file.
if (option == 1){
while(fgets(string, 100, fr3) != NULL){
firstWord(string);
printf("'%s' found. Now replace it with another name: ", string);
scanf("%s", &updated_name);
fprintf(fw1, "%s\n", updated_name);
fclose(fr3);
fclose(fw1);
exit(0);
}
}
fclose(fw1);
You're not really replacing anything, you're just asking for a new name and putting it into the file. The old name is not used in this process.
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;
}
I was under the impression that to open binary files using strings, you could simply create the string, and then implement it as the name of the file where it will read the string. This is what my lecture notes state. However I'm obveously missing something. I've used &name, name, &name[SIZE] within the fopen and each time i've gotten inBinFile == NULL unless I use the commented line. My string is correct. What's wrong? Help is much appreciated. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 25
int frstmenu(void);
int sndmenu(void);
int main()
{
int fmenu, smenu;
char name[SIZE];
FILE *inBinFile;
unsigned char numRead;
fmenu = frstmenu();
if ( fmenu !=1 && fmenu !=2 )
{
printf("\nIncorrect option\n");
fmenu = frstmenu();
}
if (fmenu == 1)
{
printf("\nEnter the file name: \n");
scanf("%s", &name[SIZE]);
/* printf("filename: %s", &name[SIZE]); */
smenu = sndmenu();
if (smenu !=1 && smenu !=2 )
{
printf("\nIncorrect option\n");
smenu = sndmenu();
}
if (smenu == 1)
{
inBinFile = fopen( name, "rb");
/* inBinFile = fopen( "stream.grc", "rb"); */
if (inBinFile == NULL)
{
fprintf(stderr, "Error opening %s", &name[SIZE]);
return(-1);
fclose(inBinFile);
}
}
return(0);
}
int frstmenu()
{
float selection;
printf("----Menu----\n");
printf("1 Open a file ( supported format: .grc )\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2): ");
scanf("%f", &selection);
return(selection);
}
int sndmenu()
{
int selection;
printf("---Menu---\n");
printf("1 Decode the sequence\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2):\n");
scanf("%i", &selection);
return(selection);
}
You probably want to say
scanf("%s", &name[0]);
or even just:
scanf("%s", name);
Your &name[SIZE] points to name + SIZE, which is beyond the allocated memory.