Compare two text files - spellchecking program in C - c

I'm writing a spellchecking program that will compare a user's text file with a dictionary to see if the words they entered are in the dictionary. If not, an error message is printed to tell the user that the specific word is wrong. I've tried a number of variations of the code below but not getting the desired results. It's something in the nested while loop that's throwing it out. This code is in draft stage I have to make it more memory efficient etc and tidy it up. I'm just interested in getting it working first. Thanks!
EDIT: Have altered the code slightly as per the tips below. It now reads the first word and says that it is in the dictionary. It then displays the second word but the dictionary scanning loop doesn't run and the program hangs. I know its the nested while loop causing the issue I just can't get my head around it!
/*Spellcheck program*/
/*Author: */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
/*Open files and test that they open*/
FILE *fp1;
FILE *fp2;
char fname[20];
char wordcheck[45];/*The longest word in the English Language is 45 letters long*/
char worddict[45];
char dummy;
int i;
int dictcount = 0;
fp1 = fopen("dictionary.txt","r");
if (fp1 == NULL)
{
printf("The dictionary file did not open.");
exit(0);
}
printf("Please enter the path of the file you wish to check:\n");
scanf("%s", fname);
scanf("%c", &dummy);
fp2 = fopen(fname, "r");
if (fp2 == NULL)
{
printf("Your file did not open, please check your filepath and try again.\n");
printf("Please enter path of file you wish to check: \n");
scanf("%20s",fname);
fp2 = fopen(fname, "r");
}
else
{
printf("Your file opened correctly\n");
}
/*When files are open, read each word from the text file into an array:*/
while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array//
{
for (i=0; wordcheck[i]; i++)
{
wordcheck[i] = tolower(wordcheck[i]);//makes all characters lower case//
}
printf("%s", wordcheck);
while(dictcount >= 0)//reads dictionary word into array//
{
dictcount = 0;
fscanf(fp1,"%s", worddict);
if(strcmp(wordcheck, worddict)==0)//compare strings//
{
printf("This word: %s is in the dictionary\n", wordcheck);
break;
}
else
{
dictcount++;
}
if(worddict == NULL)
{
printf("Your word: %s is not in the dictionary\n", wordcheck);
}
}
dictcount++;
}
fclose(fp1);
fclose(fp2);
return 0;
}

The usual way of solving this is to first read the dictionary and build a hash table. You'd then read one word at a time from the input file and flag an error if the word doesn't exist on the hash table.

Related

Why is the rest of my code is being ignored after I only have sent the first input?

I'm trying to write a program that asks for input of the name of a file and a char to be counted inside the file. But whenever I input the proper name of a file (like, "file.txt") it jumps right to the end of the program with a output like this:
"Name of the file: file.txt
Character to be counted:
The char occurs 0 times in the file "
...but I couldn't even type the char to be counted.
I know it's not an issue with the name of the file, because if I put the wrong name, it goes for the output I programmed for.
Would anyone care to explain me what's happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char filename[128];
printf("Name of the file: ");
scanf("%s", filename);
FILE * test = fopen(filename, "r");
if (test == NULL) {
printf("Error!!\n");
exit(1);
}
char inpt;
printf("Character to be counted:\n");
scanf("%c", &inpt); //gets the character to be counted
int count = 0;
char search = fgetc(test);
while(search != EOF) {
if (search == inpt) count++;
search = fgetc(test);
}
printf("The char occurs %d times in the file\n", count);
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;
}

Run - Time Check Failure #2 in C File processing

Run-Time Check Failure #2 - Stack around the variable 'filename' was corrupted.
My code works whenever I try to process the first memory location.
I can process the .txt file correctly, and I can print it.
Nevertheless, when I ask for a second memory location, the program crashes.
I tried to increase the size of filename, and I am also closing the first file, so I am clueless. Any help is acceptable! Thank you!!
This is a photo of the output
This is my code:
#include <stdio.h>
#define SIZE 100 //100 entries (100lines on a file)
#define SENSORN 100
int main()
{
FILE *fptr;
char filename[1000];
char dummy1[1];//dummy character that help me to erase what is the buffer when using gets()
int numberOfSensors;
int time[SENSORN][SIZE];
float powerConsumption[SENSORN][SIZE];
int sensor_num;
int count1 = 0;
printf("Please enter the number of sensors: ");
scanf("%d", &numberOfSensors);
//Asking for the link
//numberOfSensors - 1 because for example, if we want only 2 sensors we need sensor0 and sensor1 only
for (sensor_num = 0; sensor_num <= (numberOfSensors - 1); sensor_num++)
{
printf("Please enter the file location for sensor %d\n", sensor_num);
gets(dummy1);//clearing the buffer
gets(filename);
fptr = fopen(filename, "r");
//if file cannot be opened, then display and error message
if (fptr == NULL)
{
printf("Error opening the file! %s \n", filename);
printf("Please restart the program \n");
return 0; //exit the program
}
else
{
//Loop that let us read and print all the file by storing each value to its respective array
while (!feof(fptr))
{
//storing all the values in their respective array
//sensor_num is the sensor number
//count1 is the line number we are reading from the file
fscanf(fptr, "%d %f", &time[sensor_num][count1], &powerConsumption[sensor_num][count1]);
//making sure we have all the values stored
//Note: do not comment the following line in order to check that all values are stored
fprintf(stdout, "%d %6.2f \n", time[sensor_num][count1], powerConsumption[sensor_num][count1]);
count1++;
}
}
//closing file
fclose(fptr);
}
}
}
As Martin James said char dummy1[1]; is an absolute no-no.
Use fgets() instead of gets(), so instead of
gets(dummy1);//clearing the buffer
gets(filename);`
try,
fgets( filename, sizeof(filename) , stdin );

Comparing user input with text file and looping in C

I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)

Refining Spell Checker C program [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Compare two text files - spellchecking program in C
I am making a spellcheck program and have an operational code that works but really needs refinement.
Problem 1: I only want to read alphanumeric characters into the wordcheck array before comparing the strings. I want to get rid of all special characters. I think isalphnum would be the best option but not sure how to implement it.
Problem 2: Program is very slow and wasting a lot of memory. I don't know how else to do it though. Could anyone give me some pointers? I'm lost with using binary functions and that's what I'm sure I should be doing! Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
/*Open files and test that they open*/
FILE *fp1;
FILE *fp2;
char fname[20];
char wordcheck[45];/*The longest word in the English Language is 45 letters long*/
char worddict[45];
char dummy;
int i;
int notfound;
fp1 = fopen("dictionary.txt","r");
if (fp1 == NULL)
{
printf("The dictionary file did not open.");
exit(0);
}
printf("Please enter the path of the file you wish to check:\n");
scanf("%s", fname);
scanf("%c", &dummy);
fp2 = fopen(fname, "r");
if (fp2 == NULL)
{
printf("Your file did not open, please check your filepath and try again.\n");
printf("Please enter path of file you wish to check: \n");
scanf("%20s",fname);
fp2 = fopen(fname, "r");
}
else
{
printf("Your file opened correctly\n");
}
/*When files are open, read each word from the text file into an array:*/
while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array//
{
for (i=0; wordcheck[i]; i++)
{
wordcheck[i] = tolower(wordcheck[i]);//makes all characters lower case//
}
fseek(fp1,0,SEEK_SET);
/*printf("%s", wordcheck);//debugger*/
while(fscanf(fp1,"%s", worddict)!=EOF)
{
notfound = 1;
if(strcmp(wordcheck, worddict)==0)//compare strings//
{
printf("This word: %s is in the dictionary\n", wordcheck);//debugger//
notfound = 0;
break;
}
}
if(notfound == 1)
{
printf("%s is not in dictionary\n", wordcheck);
}
}
printf("Your file has been checked. Please check any errors found");
fclose(fp1);
fclose(fp2);
return 0;
}
You're reading the dictionary once for each input word! If your input file is long then load the dictionary first into memory and then check each word in the file. If the dictionary is long you may need to store it into a hash table or a trie. But even a simple array of dictionary words should give you an improved run time.

Resources