Program that lets a user search a file for words - c

I'm attempting to create a program that lets the user enter words and then the program searches the file for the entered word. I believe what happens in my program however is that as I enter the words it doesn't start over at 0 of the char array I'm entering it into
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string;
FILE *in_file = fopen("words.txt", "r");
//FILE *out_file = fopen("output.txt", "w");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
while(word[0]!= '0')
{
printf("please enter a word(enter 0 to end)\n");
scanf("%s",word);
while(!feof(in_file))
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word))//if match found
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
num = 0;
}
return 0;
}
Can someone help me so that it rereads into the correct position? So that when it goes to compare the words it does so correctly?

You forgot to declare memory for char *string;. Your program tries to write with fscanf(in_file,"%s",string); in unreserved memory causing undefined behavior and then very likely a crash.
Replace char *string; with char string[ MAX_WORD_LENGTH ]
There are many other problems, for example your search might only work on the first try since you are reading the file every time and once you hit EOF you won't read any more. You should set the position indicator to the beginning of the file with fseek on every search.
fseek ( in_file, 0, SEEK_SET );
Also using strstr instead of strcmp might produce better results.

Related

Get the user to enter a name but using file stream *fp

I am a beginner in c so I have a problem with get the user to input last name, a comma & then first name. However it will pass to the function call
int get_name(FILE *fp)
in my main function. I have a problem either if I have to use the arguments parameters.
Example, main (int argc, char *argv[])) or just main (void))
and from what I have been searching so far, FILE*fp cannot get the user to enter from stdin it only use to open the file(?) BUT I am required to get the user to input from keyboard and pass to the function. I have written some codes. but they don't seem to work but I am going to put down on here the one I am sure that I need a few changes most.
#define LINESIZE1024
int main(void){
FILE *fp;
char line[LINESIZE];
char first;
char last;
char comma;
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(fp = (sscanf(line,"%s %s %s",&last,&comma,&first)==3))
get_name(fp);
if(get_last_first(fp)== -1)
break;
printf("Please enter first name a comma and then last name");
}
BUT I got an error saying I can't use pass it from pointer to an integer. and many MORE but I accidentally closed my concolse and all the errors that appeared while I was trying to fix are gone. So please give me some ideas.
What about seconde code
while(1){
if(!fgets(line,LINESIZE,fp)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s %s %s",last,comma,first)==3)
get_last_first(fp);
return 0;
}
It gave me errors too. fp,last,first,comma used uninitialized in this function
OK so I think I have fixed the previous problem now. However it doesn't print the name back if the name is given correctly. Here is my fixed main code.
int main(void){
FILE *fp = stdin;
char line[LINESIZE];
char first[16];
char last[16];
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s ,%s",last,first)==2)
if(get_name(fp)==2)
printf("Your name is: %s %s\n", first, last);
}
return 0;
}
here is my function.
int get_name(FILE *fp){
char line[LINESIZE];
char last[16], first[16];
int n;
/* returns -1 if the input is not in the correct format
or the name is not valid */
if(fgets(line, LINESIZE, fp) == NULL) {
return -1;
}
/* returns 0 on EOF */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == EOF) {
return 0;
}
/* prints the name if it's valid */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == 2) {
return 2;
}
return 1;
}
I thank you people so much for taking time to read and help me. Please don't be mean :)
Seems that you are making it more complicated than needed. Don't call fgets and scanf in main. Only do that in the function get_name.
It can be something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 1024
int get_name(FILE *fp)
{
char line[LINESIZE];
char* t;
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
t = strstr(line, ",");
if (t)
{
*t = '\0';
++t;
printf("First: %s - Last: %s\n", line, t);
return 2;
}
printf("Illegal input\n");
return 0;
}
int main(int argc, char **argv)
{
get_name(stdin);
return 0;
}
If you later decide that you want to read from a file, you can reuse the function get_name without changing it at all. All you need is to change main. Like:
int main(int argc, char **argv)
{
FILE* f = fopen("test.txt", "r");
if (f)
{
get_name(f);
fclose(f);
}
else
{
printf("Open file failed\n");
}
return 0;
}
If you want to read from the keyboard, read from stdin or use scanf, which internally reads from stdin. If you want to read from a file instead, use FILE *fp, but don't forget to open the file and check if it was successful (you'll find lots of tutorials for this).
Further, when reading in strings, you need an array of characters, not a single one. Note further, that scanf can already deal with formats like "everything that is not a ',' then a ',' then a string. Note that format "[^,]" means "any character except a ',':
So you could adapt the code as follows:
#define LINESIZE 1024
int main(void){
char line[LINESIZE];
char first[LINESIZE];
char last[LINESIZE];
while(fgets(line,LINESIZE,stdin)) {
if(sscanf(line,"%[^,],%s",last,first)==2) {
printf("Read in %s ... %s\n",last,first);
}
else {
printf("Please enter first name a comma and then last name");
}
}
return 0;
}
And if your professor is picky concerning the "use FILE*", you could write:
FILE *fp = stdin;
...
while(fgets(line,LINESIZE,fp)) {
...

How to write strings in different places of a file in C

in the code below:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
FILE *fp ;
fp = fopen("out.txt", "r+");
int count = 1;
char ch ;
char userInput[5] ;
int lineNumber = 0;
while (lineNumber!= -1){
fgets(userInput, sizeof(userInput), stdin);
lineNumber = atoi(userInput);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n') //counts number of lines
count++;
if(count == lineNumber)
{
fprintf(fp, "writed %d\n", count);
fseek(fp, 0, SEEK_SET);
}
}
}
return 0;
}
I want to write a string in the line which the user gives me,i store the user answer in userInputand then convert it to the int and store it in lineNumber.
when i try to write fore example in line 90 (my file has 100 lines) two error i get:
1.the file reduce to a 91-line file (instate of remain 100 lines)
2.although i seek to first of file,no more lines written in the next loops and user inputs.
Reading a file (to count its lines) and then turning around and writing to it is tricky. Among other things, you have to do something like an fseek between the reading and the writing. So try interchanging the order of the fseek and fprintf calls:
fseek(fp, 0, SEEK_SET);
fprintf(fp, "writed %d\n", count);
Also, be aware that unless the new text you're writing ("writed ###") is exactly the same length as whatever line used to be there, the line structure of the remainder of the file is likely to get garbled.
See also this question in the C FAQ list.

Trouble finding frequency of words from a file in C

I need to write a code that will print the frequency of each word from a given file. Words like "the" and "The" will count as two different words. I've written some code so far but the command prompt stops working when I try to run the program. I just need some guidance and to be pointed in the best direction for this code, or I would like to be told that this code needs to be abandoned. I'm not very good at this so any help would be very appreciated.
#include <stdio.h>
#include <string.h>
#define FILE_NAME "input.txt"
struct word {
char wordy[2000];
int frequency;
} words;
int word_freq(const char *text, struct word words[]);
int main (void)
{
char *text;
FILE *fp = fopen(FILE_NAME, "r");
fread(text, sizeof(text[0]), sizeof(text) / sizeof(text[0]), fp);
struct word words[2000];
int nword;
int i;
nword = word_freq(text, words);
puts("\nWord frequency:");
for(i = 0; i < nword; i++)
printf(" %s: %d\n", words[i].wordy, words[i].frequency);
return 0;
}
int word_freq(const char *text, struct word words[])
{
char punctuation[] =" .,;:!?'\"";
char *tempstr;
char *pword;
int nword;
int i;
nword = 0;
strcpy(tempstr, text);
while (pword != NULL) {
for(i = 0; i < nword; i++) {
if (strcmp(pword, words[i].wordy) == 0)
break;
}
if (i < nword)
words[i].frequency++;
else {
strcpy(words[nword].wordy, pword);
words[nword].frequency= 1;
nword++;
}
pword = strtok(NULL, punctuation);
}
return nword;
}
First off all:
char *text;
FILE *fp = fopen(FILE_NAME, "r");
fread(text, sizeof(text[0]), sizeof(text) / sizeof(text[0]), fp);
Reads probably 4 bytes of your file because sizeof(text[0]) is 1 and sizeof(text) is probably 4 (depending on pointer size). You need to use ftell() or some other means to get the actual size of your data file in order to read it all into memory.
Next, you are storing this information into a pointer that has no memory allocated to it. text needs to be malloc'd or made to hold memory in some way. This is probably what is causing your program to fail to work, just to start.
There are so so SO many further issues that it will take time to explain them:
How you are using strcpy to blow up memory when you place it intotempstr
How even if that weren't the case, it would copy probably the whole file at once, unless the file had NULL terminated strings within, which it may, so perhaps this is ok.
How you compare nwords[i].wordy, even though it is not initialized and therefore garbage.
How, even if your file were read into memory correctly, you look a pword, which is unitialized for your loop counter.
Please, get some help or ask your teacher about this because this code is seriously broken.

Print out first line of input file char by char, but nothing comes to screen

So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}

Search string in a file in c

I am trying to write a program that can search a string in a file (called student.txt). I want my program to print the word if it finds the same word in the file, but its showing error.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string[50];
FILE *in_file = fopen("student.txt", "r");
//FILE *out_file = fopen("output.txt", "w");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
while(student[0]!= '0')
{
printf("please enter a word(enter 0 to end)\n");
scanf("%s", student);
while(!feof(in_file))
{
fscanf(in_file,"%s", string);
if(!strcmp(string, student))==0//if match found
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
num = 0;
}
return 0;
}
Added a sample code in its simplest form. Take care of any corner cases.
If you are searching a string "to". And file content is :
<tom took two tomatoes to make a curry> .
The output would come as 5. But in actual there is only one word "to".
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char string[50];
char student[100] = {0};
while(student[0]!= '0')
{
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
printf("please enter a word(enter 0 to end)\n");
scanf("%s", student);
while ( fscanf(in_file,"%s", string) == 1)
{
//Add a for loop till strstr(string, student) does-not returns null.
if(strstr(string, student)!=0) {//if match found
num++;
}
}
printf("we found the word %s in the file %d times\n",student,num );
num = 0;
fclose(in_file);
}
return 0;
}
As rightly said by my fellow colleagues we need to have one more loop to traverse for any further instance of same word in the same line.
Note: In case if you want the word "to" only to be counted, make sure to check the "string - 1" and "string + 1" character for all the possible word delimiters like space, comma, full stop, newline, Exclamatory, ampersand, equals and any other possibilities. One simple way would be to use strtok which would tokenize the buffer into words based on delimiters specified in the argument. Checkout how to use strtok.
http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
You should read (create a function) words from the file. And by words I mean array of non-whitespace characters surrounded by whitespaces such as blank space (but don't record the white spaces in the words list). Then search through the word list (or through the words on the fly) to look for the required word.
Either use variable student in the last printf() line or place your matched text in variable word and also check your if condition.

Resources