search string from file and store it in struct using c - c

i have a structure like so:
struct profile {
char firstName[15], lastName[15];
int age, phoneNo;
};
and i've written a code to store the text data from this structure into a text file, like so:
int main()
{
FILE* fPtr;
fPtr = fopen("profile.txt", "a");
printf("\n\nPlease enter your details:");
struct profile c;
printf("\n\nEnter your first name: ");
gets(c.firstName);
printf("\nEnter your last name: ");
gets(c.lastName);
printf("\nEnter your age: ");
scanf("%d", &c.age);
printf("Enter your phone number: ");
scanf("%d", &c.phoneNo);
fprintf(fPtr, "%s#%s#%dy#%d#\n", c.firstName, c.lastName, c.age, c.phoneNo);
fclose(fPtr);
return 0;
}
the code above will store the data input into the struct into a text file of strings, each string is one profile, and each value is separated by a '#', like below:
John#Doe#35y#0123456789#
Mary Ann#Brown#20y#034352421#
Nicholas#McDonald#15y#0987654321#
i'd like to know if there's a way i can search for a certain name/age/phoneNo from the text file, select the entire string of the corresponding profile and put each value back into a structure as above so that i can display it? i've separate each value with a '#' so that the program can use the # to differentiate between each value when it reads from the file but i'm not sure how i can separate it when i read the data. should i use fgets ? i'm new to C so i'd appreciate it if someone could explain it me how.

This is not exactly what you are looking for , but it helps you start using fgets and how to search for entries(only strings now).
#include <stdio.h>
#include <string.h>
#define MYFILE "profile.txt"
#define BUFFER_SIZE 50
int main()
{
char nametoSearch[BUFFER_SIZE];
char Names[BUFFER_SIZE];
FILE* fPtr;
if (fPtr = fopen(MYFILE, "r"))
{
// flag to check whether record found or not
int fountRecord = 0;
printf("Enter name to search : ");
//use fgets if you are reading input with spaces like John Doe
fgets(nametoSearch, BUFFER_SIZE, stdin);
//remove the '\n' at the end of string
nametoSearch[strlen(nametoSearch)-1] = '\0';
while (fgets(Names, BUFFER_SIZE, fPtr))
{
// strstr returns start address of substring in case if present
if(strstr(Names,nametoSearch))
{
printf("%s\n", Names);
fountRecord = 1;
}
}
if ( !fountRecord )
printf("%s cannot be found\n",nametoSearch);
fclose(fPtr);
}
else
{
printf("file %s cannot be opened\n", MYFILE );
}
return 0;
}

Related

How to write, read and delete a file in a single script in C programming

I created a file and filled it with some entries. However, I want to read this file and show it on the screen. Also, after showing the entries, I want it to be deleted with my permission. But I am stuck at this point please help me.
EDIT: Code is updated but still couldn't figure it out how to do :/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
int main() {
FILE *f1;
f1 = fopen("C:\\FurkanArslan.txt", "r+");
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); scanf("%s", name);
printf("Surname:"); scanf("%s", surname);
printf("Country:"); scanf("%s", country);
printf("City :"); scanf("%s", city);
printf("Gender :"); scanf("%s", gender);
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
fclose(f1);
printf("\n<<<<<%d data has been successfully saved!>>>> \n", count * 5);
printf("-------------------------------------\n");
f1 = fopen("C:\\FurkanArslan.txt", "r");
char c, answer;
while ((c = fgetc(f1)) != EOF)
putchar(c); // In this part I displayed file on the screen.
printf("\n\n <<<< %d entries are displayed on the screen! >>>>", count * 5);
printf("\n\nWould you like to remove your file [Y/N] ?");
scanf(" %c", &answer);
if (answer == 'y' || answer == 'Y') {
remove("f1");
printf("\n\n***File successfully removed!");
}
return 0;
}
In order to show the content of a file you have to open it and read it letter by letter, after that, you can use the putchar function to output the current character
FILE *fp = fopen("path/to/file.txt","r");
char c;
while((c=fgetc(fp))!=EOF)
putchar(c);
fclose(fp);
after that to remove a file you need to use the remove function, which receives the name of the file as paramter.
remove("my_file.txt");
There are multiple issues in your code:
there is no need to make the variables and arrays global, just define them in the body of the main() function.
you should tell scanf() the maximum number of characters to store in the destination array with a length specifier in the format string (eg: "%19s") and check for conversion success.
the variable c used in the reading loop must have type int for proper detection of EOF. fgetc() returns a positive byte value if successful and the special negative value EOF at end of file.
you do not need to reopen the file after writing to it. Sine you opened it for update mode, you can just seek back to the beginning of the file with rewind(f1) or fseek(f1, 0L, SEEK_SET).
the file is open for read and update mode ("r+"): it will fail if the file does not exist. You should open it in write and update mode with "w+" to create or truncate it.
you should check that fopen succeeds at opening the file, otherwise you invoke undefined behavior passing a null stream pointer to fprintf.
to remove the file, remove() takes the filename as its argument. You must close the file before attempting to remove it.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *filename = "C:\\FurkanArslan.txt";
char name[20], surname[20], city[30], country[30], gender[15];
int count = 0;
FILE *f1 = fopen(filename, "w+");
if (f1 == NULL) {
printf("Cannot open file %s.\n", filename);
return 1;
}
while (count < 10) { // every step provides 5 new data, so 5*10 will provide 50 data in total.
printf("\n*Please enter required information: \n");
printf("Name :"); if (scanf("%19s", name) != 1) break;
printf("Surname:"); if (scanf("%19s", surname) != 1) break;
printf("Country:"); if (scanf("%29s", country) != 1) break;
printf("City :"); if (scanf("%29s", city) != 1) break;
printf("Gender :"); if (scanf("%14s", gender) != 1) break;
fprintf(f1, " %s | %s | %s | %s | %s\n\n", name, surname, gender, city, country);
count++;
}
printf("\n<<<<< %d data has been successfully saved to %s! >>>>\n",
count * 5, filename);
printf("-------------------------------------\n");
rewind(f1);
int c;
while ((c = fgetc(f1)) != EOF)
putchar(c);
printf("\n\n <<<< %d entries are displayed on the screen! >>>>\n", count);
fclose(f1);
printf("\nWould you like to remove your file [Y/N] ?");
char answer;
if (scanf(" %c", &answer) == 1 && (answer == 'y' || answer == 'Y')) {
if (remove(filename)) {
printf("\n\n***Error removing file %s: %s\n",
filename, strerror(errno));
} else {
printf("\n\n***File %s successfully removed!\n", filename);
}
}
return 0;
}

Reading and writing binary files in C

These are 2 separate applications.
In the first one, I tried to store employee details like name, age and salary in the binary file named emp.bin.
In the second application, I tried to view the contents of the file but in place of the name, only the first character appears.
I tried printing each character separately, and it turns out that there's 3 null characters '\n' after each letter in the name that is why it is not printing after the first character.
"Write" application code:
//Receives records from keyboard and writes them to a file in binary mode
#include <stdio.h>
int main()
{
FILE *fp;
char another = 'Y';
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen("emp.bin", "wb");
if (fp == NULL)
{
puts("Cannot open the file.");
return 1;
}
while(another == 'Y')
{
printf("Enter the employee name, age and salary: ");
scanf("%S %d %f", e.name, &e.age, &e.bs);
while(getchar() != '\n');
fwrite(&e, sizeof(e), 1, fp);
printf("Add another record? (Y/N)");
another = getchar();
}
fclose(fp);
return 0;
}
"Read" application code:
//Read records from binary file and displays them on VDU
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *fp;
struct emp
{
char name[40];
int age;
float bs;
} e;
fp = fopen("emp.bin", "rb");
if (fp == NULL)
{
puts("Cannot open the file.");
return 1;
}
while (fread(&e, sizeof(e), 1, fp) == 1)
{
printf("\n%s \t %d \t $%.2f\n", e.name, e.age, e.bs);
}
fclose(fp);
}
Here's the input and output:
How can I correct this code to make it print the whole name?
The problem is in the "writer" application, even before the actual write is performed.
When you get data from the user
scanf("%S %d %f", e.name, &e.age, &e.bs);
you use format %S (capital letter "S". Format specifiers are case sensitive!). As we can read in the printf man page
S
(Not in C99, but in SUSv2.) Synonym for ls. Don't use.
this leads us to %ls format specifier that is described in the following way
s
[...] If an l modifier is present: The const wchar_t * argument is expected to be a pointer to an array of wide characters. Wide characters from the array are converted to multibyte characters
Talking about Windows source we have:
S
Opposite-size character string, up to first white-space character (space, tab or newline). [...]
When used with scanf functions, signifies wide-character array; when used with wscanf functions, signifies single-byte-character array [...]
So, basically, you are reading characters from stdin and converting them to wide chars. In this case every character takes sizeof(wchar_t). Probably in your system this size is 4.
What you need is simply %s format specifier. And since your name array has size 40, I suggest using
scanf("%39s", e.name );
to get the name from user. In this way up to 39 characters will be written, being the 40th reserved to the string terminator '\0'.
As noted by Roberto in his answer, the problem is the %S conversion specifier, which is a typo, you should use %s.
Note however that there are other issues which might pose problems:
you should tell scanf() the maximum number of characters to read for the employee name, otherwise scanf() may write beyond the end of the destination array if input is too long.
if both programs run on separate systems with different endianness, the numbers will be incorrect on the receiving end because their bytes will be stored in the opposite order. For this reason, endianness should be specified and handled explicitly in binary files. Text format tends to be preferred for data transmission.
Here is a modified version:
//Receives records from keyboard and writes them to a file in binary mode
#include <stdio.h>
int main() {
FILE *fp;
char another = 'Y';
struct emp {
char name[40];
int age;
float bs;
} e;
int c;
fp = fopen("emp.bin", "wb");
if (fp == NULL) {
puts("Cannot open the file.");
return 1;
}
while (another == 'Y') {
printf("Enter the employee name, age and salary: ");
if (scanf("%39s %d %f", e.name, &e.age, &e.bs) != 3)
break;
while ((c = getchar()) != EOF && c != '\n')
continue;
if (fwrite(&e, sizeof(e), 1, fp) != 1)
break;
printf("Add another record? (Y/N)");
another = getchar();
}
fclose(fp);
return 0;
}
"Read" application code:
//Read records from binary file and displays them on VDU
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp;
struct emp {
char name[40];
int age;
float bs;
} e;
fp = fopen("emp.bin", "rb");
if (fp == NULL) {
puts("Cannot open the file.");
return 1;
}
while (fread(&e, sizeof(e), 1, fp) == 1) {
printf("\n%s \t %d \t $%.2f\n", e.name, e.age, e.bs);
}
fclose(fp);
return 0;
}

How to modify contents in a file?

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;
}

How to edit data of a file File Handling C

I'm wondering if I could use fseek() on editing the value of a variable on a file. All the tutorials I saw online were about editing a text, but how can I use fseek() to edit a value.
Here's how my program works: The user inputs a name, gender, and age. The user can input as many data as they want. Now, the user searches a name; and the gender, and age of that name will display. The user is then prompted to edit the age. After inputting a new age, the file will now be edited, with the new age written.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data
{
char name[30];
char gender[10];
int age;
};
int main(void)
{
struct data client;
FILE* fp;
char ch = 0;
do
{
printf("Enter Name: ");
scanf("%s", client.name);
printf("Enter Gender: ");
scanf("%s", client.gender);
printf("Enter Age: ");
scanf("%d", &client.age);
fp = fopen("data.txt", "ab");
fwrite(&client, sizeof(client), 1, fp);
fclose(fp);
printf("continue? \n");
scanf(" %c", &ch);
} while (ch != 'n'); // continuously appends file till letter n is read;
char input[30]; // user input
printf("name?\n");
scanf("%s", input);
struct data Read;
fp = fopen("data.txt", "rb");
int newAge;
while (fread(&client, sizeof(client), 1, fp))
{
if (strcmp(client.name, input) == 0) // compare variable with user input
{
printf("%s", client.name);
printf(" %s", client.gender);
printf(" %d y/o", client.age);
printf("\n");
printf("enter new age");
scanf("%d", &newAge);
//fseek function
}
}
return 0;
}
Hope somebody can help.

Sorting data on text file in C

I found this exercise where I had to create a data structures, read some inputs, store the inputs on the "appropriate" data structure and then print everything to a text file.
I am looking forward to adding a function to order the hotel list according to the stars number, so if an hotel has 5 stars, it will be at the top of the list. Is it possible to do that? Can I do that with arrays?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct inputs {
char nome[30];
char via[30];
char stars[30];
int num;
};
int main(void)
{
struct inputs inputs = {"", "", ""};
FILE *cfPtr; // cfPtr = clients.txt file pointer
// fopen opens file. Exit program if unable to create file
if ((cfPtr = fopen("clients.txt", "w")) == NULL) {
puts("File could not be opened");
}
else {
puts("Enter the account, name, and balance.");
puts("Enter EOF to end input.");
printf("%s", "? ");
//scanf("%[^\n]s%[^\n]s%[^\n]s", inputs.via, inputs.nome, inputs.stars);
fgets(inputs.nome, 30, stdin);
inputs.nome[strcspn(inputs.nome,"\n")] = '\0';
fgets(inputs.via, 30, stdin);
inputs.via[strcspn(inputs.via,"\n")] = '\0';
fgets(inputs.stars, 30, stdin);
inputs.stars[strcspn(inputs.stars,"\n")] = '\0';
inputs.num = strlen(inputs.stars);
//printf("%s%s%s", inputs.nome, inputs.via, inputs.stars);
// write account, name and balance into file with fprintf
while (!feof(stdin)) {
fprintf(cfPtr, "%s; %s; %s; %d\n", inputs.nome, inputs.via, inputs.stars, inputs.num);
/*scanf("%[^\n]s", inputs.via);
scanf("%[^\n]s", inputs.nome);
scanf("%[^\n]s", inputs.stars);*/
fgets(inputs.nome, 30, stdin);
inputs.nome[strcspn(inputs.nome,"\n")] = '\0';
fgets(inputs.via, 30, stdin);
inputs.via[strcspn(inputs.via,"\n")] = '\0';
fgets(inputs.stars, 30, stdin);
inputs.stars[strcspn(inputs.stars,"\n")] = '\0';
inputs.num = strlen(inputs.stars);
}
fclose(cfPtr); // fclose closes file
}
}
I would suggest creating a struct type to represent one hotel, and then create an array of instances of the struct type. For instance the type could be as follows.
struct Hotel {
uint8_t stars;
char name[HOTELNAMESIZE];
};
struct Hotel hotels[NRHOTELS];
Now you can implement a sort function that sorts the hotels array based on hotels[i].stars. Of course this is a very simple implementation that has a hardcoded HOTELNAMESIZE and NRHOTELS value, but could be a decent starting point.

Resources