Posted by : Waqas Javed Saturday, 17 January 2015

This code demonstrate the filing part of C language. This program is built to save name of users in a file on hard disk you can also retrieve that file from hard disk using this program and could also search how many times a name is found in a file.

The program also uses some basic function of  C++ that are just for convenience  you can replace them by C language

printf("some text"); is used as cout << "some text";
scanf(&d) id used as cin >> d;

so dont worry if you need code in C only you could replace it

The special data type FILE is used used to create stream for input or output data on hard disk.
in fopen function a mean file is opened in append mode, r mean read mode, w mean write mode.
system("cls"); is iostream part so if you want avoid C++ you could simply delete it that will not effect the code.  this function just delete all data from console and clear it.


#include<iostream>
#include<stdio.h>
#include<conio.h>

using namespace std;

void main() {
FILE* myFile;
FILE* readFile;
char name[20];
int con = 1;
char temp;

while (true){
myFile = fopen("names.txt", "a");
cout << "Press 1 to Enter name..2 to search name.. 3 to display file: ";
cin >> con;

system("cls");

//enter name
if (con == 1){

cout << "Enter A name: ";
cin >> name;

fprintf(myFile, "%s", name);
fprintf(myFile, "%c", '-');

cout << "\nNAME ENTERED\n";
}

fclose(myFile);
//search in file
int counter = 0;
readFile = fopen("names.txt", "r");
if (con == 2){
cout << "Enter a name to search:";
cin >> name;
int matched = 0;
int chars = strlen(name);

while (fscanf(readFile, "%c", &temp) == 1){
if(temp!= '-'){
if(name[matched] == temp){
matched++;
} else{
matched = 0;
}

} else if(matched == chars){
counter++;
matched = 0;
} else{
matched = 0;
}



}
}

if(counter > 0){
cout << "\n\aName is found in file " << counter << " times.\n";
} else if(con == 2) {
cout << "Name is not in file...\n";
}

if(con == 3){
//display file
fclose(readFile);
fopen("names.txt", "r");
cout << "Display File text:\n";

while (fscanf(readFile, "%c", &temp)== 1){
if(temp != '-'){
printf("%c", temp);
} else {
printf("\n");
}
}
}

printf("\n");
}

_getch();
}

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Popular Post

Powered by Blogger.

- Copyright © BSCS -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -