How do I count the number of characters in a file? - c

I have copied the contents of a file to another file and I am trying to get the line, word, and character count. The code I have right now displays the number of lines and words in the file content. Now I need to display the character count but I am unsure of how to do that. I am guessing a for loop? But I am not sure.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_WORD_LEN 100
#define MAX_LINE_LEN 1000
#define ipsumFile "Lorem ipsum.txt"
#define ipsumCopy "Lorem ipsum_COPY.txt"
int wordCount(FILE *fp);
int charCount(FILE *fp);
int sendContentTo(FILE *fp, FILE *out);
int getWordAt(FILE *fp, int pos, char *word);
int appendToFile(char *fileName, char *newText);
int main(void)
{
FILE *fp, *fp2; //"file pointer"
int ch; //place to store each character as read
//open Lorem ipsum.txt for read
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
//open Lorem ipsumCopy for writing
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
//print out and count all words in Lorem ipsum.txt
int numOfWords = wordCount(fp);
//print out and count all lines in Lorem ipsum.txt
int numOfLines = sendContentTo(fp, stdout);
//copy the content of Lorem ipsum.txt into a new file (ipsumCopy)
numOfLines = sendContentTo(fp, fp2);
fclose(ipsumFile);
fclose(ipsumCopy);
// close Lorem ipsum.txt
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
if (fclose(fp2) != 0)
fprintf(stderr, "Error closing copy\n");
return 0;
}
int sendContentTo(FILE *in, FILE *out)
{
fprintf(stdout, "Performing file copy...\n\n");
//start at the beginning of the file
rewind(in);
// array to hold one line of text up to 1000 characters
char line[MAX_LINE_LEN];
int lineCount = 0;
// read one line at a time from our input file
while (fgets(line, MAX_LINE_LEN, in) != NULL)
{
//send line we just read to output.
fprintf(out, "%s", line);
//count the lines
lineCount++;
}
fprintf(stdout, "\nFinished line count.\n");
fprintf(stdout, "Count is: %d.\n\n", lineCount);
// Return how many text lines
// we've processed from input file.
return lineCount;
}
// Read content from file one character at a time.
// Returns number of total characters read from the file.
int charCount(FILE *fp)
{
fprintf(stdout, "Performing char count...\n\n");
rewind(fp);
int charCount = 0;
char ch;
//print out each character, and return the
// number of characters in the file.
fprintf(stdout, "\nFinished character count. \n");
fprintf(stdout, "Count is: %d. \n\n", charCount);
return charCount;
}
// Read content from file one word at a time.
// Returns number of total words read from the file.
int wordCount(FILE *fp)
{
fprintf(stdout, "Performing word count...\n\n");
rewind(fp);
char word[MAX_WORD_LEN];
int wordCount = 0;
while (fscanf(fp, "%s", word) == 1)
{
// Send entire word string
// we just read to console
puts(word);
//count the word
wordCount++;
}
fprintf(stdout, "\nFinished word count.\n");
fprintf(stdout, "Count is: %d.\n\n", wordCount);
return wordCount;
}

You don't need to write different function for counting the number of lines, words, and characters in a file. You can do it in a single parsing of file character by character and while parsing, in order to copy the content of file to another file, you can write the characters to another file. You can do:
#include <stdio.h>
#include <stdlib.h>
int count_and_copy(const char * ipsumFile, const char * ipsumCopy)
{
unsigned int cCount = 0, wCount = 0, lCount = 0;
int incr_word_count = 0, c;
FILE *fp, *fp2;
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
while((c = fgetc(fp)) != EOF)
{
fputc(c, fp2); // write character c to the copy file
cCount++; // character count
if(c == '\n') lCount++; // line count
if (c == ' ' || c == '\n' || c == '\t')
incr_word_count = 0;
else if (incr_word_count == 0) {
incr_word_count = 1;
wCount++; // word count
}
}
fclose (fp);
fclose (fp2);
printf ("Number of lines : %u\n", lCount);
printf ("Number of words : %u\n", wCount);
printf ("Number of characters : %u\n", cCount);
return 0;
}
int main()
{
/* Assuming, you want to count number of lines, words
* and characters of file1 and copy the contents of file1
* to file2.
*/
count_and_copy("file1", "file2");
return 0;
}

I suppose that the following approach will work:
void *cw(const char *fname)
{
FILE *f = fopen(fname, "r");
if (f == NULL) {
fprintf(stderr, "fopen(%s): %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
int bc = 0; /* bytes counter */
int wc = 0 ; /* words counter */
int nlc = 0; /* new lines counter */
const int in_word_state = 0;
const int out_word_state = 1;
int state = out_word_state;
int c = 0;
for (;;) {
c = fgetc(f);
if (ferror(f) != 0) {
perror("fgetc");
goto error;
}
if (feof(f))
break;
if (c == '\n')
nlc++;
if (c == ' ' || c == '\t' || c == '\n')
state = out_word_state;
if (state == out_word_state) {
state = in_word_state;
wc++;
}
bc++;
}
if (fclose(f) == EOF) {
perror("fclose");
goto error;
}
printf("w: %d, c: %d, l:%d\n", wc, bc, nlc);
error:
if (f != NULL) {
if (fclose(f) == EOF) {
perror("fclose");
}
}
exit(EXIT_FAILURE);
}

Related

Its supposed to be a simple keyword search function imitating a national instruments function. Why wont it work?

I am trying to write this program in C. The intent of the program is to run a designated keyword search on one file, find the information stored on that line, and then copy that information to the same location in another file. The keyword is utilized to determine the line in the file to be copied and to replace. I am using Microsoft Visual. Built in ".c" I am receiving this message: " (process 24612) exited with code -1073741819"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable : 4996)
#define MAX_LENGTH 1000
void locate(const char* keyword, int start, int end, int lineCount, char* line, int* a, int* a_index) {
if (lineCount >= start && lineCount <= end) {
if (strstr(line, keyword) != NULL) {
a[*a_index] = lineCount;
(*a_index)++;
}
}
}
void replaceLines(const char* filename1, const char* filename2, const char* keyword, int start, int end) {
char buffer[MAX_LENGTH];
char line[MAX_LENGTH];
int lineCount = 0;
int i;
int a[20];
int a_index = 0;
// Open the first file in read
FILE* file1 = fopen(filename1, "r");
if (file1 == NULL) {
printf("Error opening file %s\n", filename1);
exit(1);
}
// Open the second file in read
FILE* file2 = fopen(filename2, "r");
if (file2 == NULL) {
printf("Error opening file %s\n", filename2);
exit(1);
}
// Read the first file into a buffer
while (fgets(buffer + strlen(buffer), MAX_LENGTH, file1)) {
;
}
// Close the first file
fclose(file1);
// Open the first file in read/write
file1 = fopen(filename1, "w+");
if (file1 == NULL) {
printf("Error opening file %s\n", filename1);
exit(1);
}
// Read file1 line by line
while (fgets(line, MAX_LENGTH, file1)) {
lineCount++;
locate(keyword, start, end, lineCount, line, a, &a_index);
}
lineCount = 0; //reset lineCount
// Read file2 line by line and copy line from file2 to buffer using the line found in file1 keyword search
while (fgets(line, MAX_LENGTH, file2)) {
lineCount++;
if (lineCount >= start && lineCount <= end) {
if (strstr(line, keyword) != NULL) {
strncpy(buffer + a[a_index] * MAX_LENGTH, line, MAX_LENGTH);
}
}
}
// Close the second file
fclose(file2);
// Write the modified buffer back to file1
fputs(buffer, file1);
// Close the first file
fclose(file1);
}
int main(void) {
replaceLines("c:\\LocationFolder\\Overwrite.txt", "c:\\LocationFolder\\Baseline.txt", "Simulated Primary Open", 3, 22);
return 0;
}

Line counting in C but exclude empty lines

I've got the following program, but there is a problem. First the program part that does not work:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
FILE *fp2;
char ch;
char fnamer[100];
char fnamer2[100]; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s",&fnamer);
fp=fopen(fnamer,"r");
if(fp==NULL)
{
printf("Error!");
exit(1);
}
printf("\n\nPlease Enter the Full Path of the Image file you want to write to: \n");
scanf("%s",&fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
printf("Error!");
exit(1);
}
else
{
// printf("test\n");
}
int line_number = 0;
int charsOnLine = 0;
fprintf(fp2, "%d: ", ++line_number); /* put line number in output file */
printf("%d: ", line_number);
while((ch = fgetc(fp)) != EOF )
{
//printf("test2");
fputc(ch,fp2);
printf("%c", ch);
if ( ch != '\n' && charsOnLine ==0 )
{
fprintf(fp2, "%d:", ++line_number ); /* put line number in output file */
printf("%d: ", line_number);
}
// if (ch != '\n' && charsOnLine 0 ){
// fprintf(fp2, "%c", ch);
// printf("%d", ch);
// }
}
fclose;
fclose(fp);
// fclose(fp2);
// getch();
}
The program needs to count the lines, give them a number but skip the blank lines. But here is the problem: when I run this code it gives all the chars a number.
You could use a flag to remember when you have just started a new line. The first time you see a char not equal to '\n', you print the line number and clear the flag.
Something like:
int line_number = 0;
int newLine = 1;
while((ch = fgetc(fp)) != EOF )
{
if (ch == '\n')
{
newLine = 1;
}
else
{
if (newLine)
{
fprintf(fp2, "%d:", ++line_number );
printf("%d: ", line_number);
newLine = 0;
}
}
fputc(ch,fp2);
printf("%c", ch);
}
From what I understand, the program needs to count the lines and append their content.
Then I would search for '\n' char, rather than skipping it with if (ch != '\n')
int main()
{
FILE *fp;
FILE *fp2;
char ch;
char fnamer[100];
char fnamer2[100]; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s",&fnamer);
fp=fopen(fnamer,"r");
if(fp==NULL)
{
printf("Error!");
exit(1);
}
printf("\n\nPlease Enter the Full Path of the Image file you want to write to: \n");
scanf("%s",&fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
printf("Error!");
exit(1);
}
int line_number = 0;
fprintf(fp2, "%d: ", ++line_number );
while((ch = fgetc(fp)) != EOF )
{
if ( ch == '\n' )
{
fprintf(fp2, "%d: ", ++line_number ); /* put line number in output file */
}
else {
fputc(ch,fp2); /* put the char in the corresponding line */
}
}
fclose(fp);
fclose(fp2);
}

Convert and count upper case and lowercase characters

I am writing a C program to convert all uppercase characters to lowercase and all lowercase to uppercase from a file.
I also want to count the characters read and the number of characters converted to uppercase and characters converted to lowercase.
I am able to convert the characters but unable to figure out how to count them.
Example;
Hello World!
Output;
hELLO wORLD!
Read 13 characters in total.
8 converted to uppercase.
2 converted to lowercase.
Here's my code;
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INPUT_FILE "input.txt"
#define OUTPUT_FILE "output.txt"
int main()
{
FILE *inputFile = fopen(INPUT_FILE, "rt");
if (NULL == inputFile) {
printf("ERROR: cannot open the file: %s\n", INPUT_FILE);
return -1;
}
// 2. Open another file
FILE *outputFile = fopen(OUTPUT_FILE, "wt");
if (NULL == inputFile) {
printf("ERROR: cannot open the file: %s\n", OUTPUT_FILE);
return -1;
}
int c;
int ch;
int upper = 0;
int lower = 0;
int count = 0;
while (EOF != (c = fgetc(inputFile))) {
ch = islower(c)? toupper(c) : tolower(c);
fputc(ch, outputFile);
}
while (EOF != (c = fgetc(inputFile))) {
if (isupper(c))
{
upper++;
}
else if (islower(c))
{
lower++;
}
fputc(upper, outputFile);
fputc(lower, outputFile);
}
fclose(inputFile);
fclose(outputFile);
return 0;
}
Your main problem is that you are using 2 loops to read input file.
Your second loop should rewind the file before to start re-reading the file.
You can count and convert with a single loop.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INPUT_FILE "input.txt"
#define OUTPUT_FILE "output.txt"
int main()
{
FILE *inputFile = fopen(INPUT_FILE, "rt");
if (NULL == inputFile) {
printf("ERROR: cannot open the file: %s\n", INPUT_FILE);
return -1;
}
// 2. Open another file
FILE *outputFile = fopen(OUTPUT_FILE, "w");
if (NULL == outputFile) {
printf("ERROR: cannot open the file: %s\n", OUTPUT_FILE);
return -1;
}
int ch;
int upper = 0;
int lower = 0;
int count = 0;
while (EOF != (ch = fgetc(inputFile)))
{
if (isalpha(ch))
{
if (islower(ch))
{
ch = toupper(ch);
upper++;
}
else
{
ch = tolower(ch);
lower++;
}
count++;
}
fputc(ch, outputFile);
}
fprintf(outputFile, "\nTotal: %d\nToUpper: %d\nToLower: %d\n", count, upper, lower);
fclose(inputFile);
fclose(outputFile);
return 0;
}
Take also note that you have to check if a read char is an alpha char before to convert the case, as the isalpha call inside the loop do.

Compare each line from two different files and print the lines that are different in C

Supposing that I have two files like this:
file1.txt
john
is
the new
guy
file2.txt
man
the old
is
rick
cat
dog
I'd like to compare first line from file1 with all the lines from file2 and verify if it exist. If not, go two the second line from file1 and compare it with all the lines from file2.. and so on until eof is reached by file1.
The output that I expect is:
john
the new
guy
How I thought this should be done:
read file1 and file2
create a function which returns the line number of each of them
take the first line from file1 and compare it to all the lines from file2
do this until all the lines from file1 are wasted
Now, I don't know what I'm doing wrong, but I don't get the result that I expect:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int countlines(char *filename)
{
int ch = 0, lines = 0;
FILE *fp = fopen(filename, "r");
if (fp == NULL)
return 0;
do {
ch = fgetc(fp);
if (ch == '\n')
lines++;
} while (ch != EOF);
if (ch != '\n' && lines != 0)
lines++;
fclose(fp);
return lines;
}
int main(int argc, char *argv[])
{
FILE *template_file = fopen(argv[1], "r");
FILE *data_file = fopen(argv[2], "r");
char buffer_line_template_file[100];
char buffer_line_data_file[100];
if (argc != 3)
{
perror("You didn't insert all the arguments!\n\n");
exit(EXIT_FAILURE);
}
if (template_file == NULL || data_file == NULL)
{
perror("Error while opening the file!\n\n");
exit(EXIT_FAILURE);
}
int counter = 0;
for (int i = 0; i < countlines(argv[1]); i++)
{
fgets(buffer_line_template_file, 100, template_file);
for (int j = 0; j < countlines(argv[2]); j++)
{
fgets(buffer_line_data_file, 100, data_file);
if (strcmp(buffer_line_template_file, buffer_line_data_file) != 0)
{
counter++;
printf("%d", counter);
}
}
}
printf("\n\n");
return 0;
}
Could someone please point me into the right direction ? For testing purposes I created a counter at the end which was a part of a small debug. There should be the print() function
As per #chux answer I got the following simplified code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *template_file = fopen(argv[1], "r");
FILE *data_file = fopen(argv[2], "r");
char buffer_line_template_file[100];
char buffer_line_data_file[100];
if (argc != 3)
{
perror("You didn't insert all the arguments!\n\n");
exit(EXIT_FAILURE);
}
if (template_file == NULL || data_file == NULL)
{
perror("Error while opening the file!\n\n");
exit(EXIT_FAILURE);
}
while(fgets(buffer_line_template_file, 100, template_file))
{
buffer_line_template_file[strcspn(buffer_line_template_file, "\n")] = '\0';
rewind(data_file);
while (fgets(buffer_line_data_file, 100, data_file))
{
buffer_line_data_file[strcspn(buffer_line_data_file, "\n")] = '\0';
if (strcmp(buffer_line_template_file, buffer_line_data_file) != 0)
{
printf("%s\n", buffer_line_template_file);
}
}
}
printf("\n\n");
return 0;
}
The above code is giving me the following output, which is not what is expected:
john
john
john
john
john
john
is
is
is
is
is
the new
the new
the new
the new
the new
the new
guy
guy
guy
guy
guy
guy
Problems with OP's code
Imprecise definition of line.
Excessive recalculation
Fuzzy determination of the number of lines in a file.
Unlike string, which has a precise definition in C, reading a line is not so well defined. The primary specificity issue: does a line contain the trailing '\n'. If the first answer is Yes, then does the last text in a file after a '\n' constitute a line? (Excessively long lines are another issue, but let us not deal with that today.)
Thus possibly some lines end with '\n' and others do not, fooling strcmp("dog", "dog\n").
The easiest solution is to read a line until either 1) a '\n' is encountered, 2) EOF occurs or 3) line buffer is full. Then after getting a line, lop off the potential trailing '\n'.
Now all lines code subsequently works with have no '\n'.
fgets(buffer_line_template_file, 100, template_file);
buffer_line_template_file[strcspn(buffer_line_template_file, "\n")] = '\0';
OP's loop is incredible wasteful. Consider a file with 1000 lines. Code will loop, calling 1000 times countlines() (each countlines() call reads 1000 lines) times when one countlines() call would suffice.
// for (int j = 0; j < countlines(argv[2]); j++)
int j_limit = countlines(argv[2]);
for (int j = 0; j < j_limit; j++)
There really is no need to count the line anyways, just continue until EOF (fgets() returns NULL). So no need to fix its fuzzy definition. (fuzzy-ness concerns same issues as #1)
int counter = 0;
for (fgets(buffer_line_template_file, 100, template_file)) {
buffer_line_template_file[strcspn(buffer_line_template_file, "\n")] = '\0';
rewind(data_file);
while ((fgets(buffer_line_data_file, 100, data_file)) {
buffer_line_data_file[strcspn(buffer_line_data_file, "\n")] = '\0';
if (strcmp(buffer_line_template_file, buffer_line_data_file) != 0) {
counter++;
printf("%d", counter);
}
}
}
Other simplifications possible - for another day.
FWIW, following counts lines of text allowing the last line in the file to optionally end with a '\n'.
unsigned long long FileLineCount(FILE *istream) {
unsigned long long LineCount = 0;
rewind(istream);
int previous = '\n';
int ch;
while ((ch = fgetc(inf)) != EOF) {
if (previous == '\n') LineCount++;
previous = ch;
}
return LineCount;
}
Note that this function may get a different result that fgets() calls. Consider a file of one line of 150 characters. fgets(..., 100,...) will report 2 lines. FileLineCount() reports 1.
[Edit] Updated code to conform to OP functionality.
int found = 0;
while (fgets(buffer_line_data_file, 100, data_file))
{
buffer_line_data_file[strcspn(buffer_line_data_file, "\n")] = '\0';
if (strcmp(buffer_line_template_file, buffer_line_data_file) == 0)
{
found = 1;
break;
}
}
if (!found) printf("%s\n", buffer_line_template_file);
This program prints the diff of two files file1.txt and file2.txt.
#include<stdio.h>
#include <stdlib.h>
#include <memory.h>
int main() {
FILE *fp1, *fp2;
int ch1, ch2;
char fname1[40], fname2[40];
char *line = NULL;
size_t len = 0;
ssize_t read;
char *line2 = NULL;
size_t len2 = 0;
ssize_t read2;
fp1 = fopen("file1.txt", "r");
fp2 = fopen("file2.txt", "r");
if (fp1 == NULL) {
printf("Cannot open %s for reading ", fname1);
exit(1);
} else if (fp2 == NULL) {
printf("Cannot open %s for reading ", fname2);
exit(1);
} else {
while ((read = getline(&line, &len, fp1)) != -1 && (read2 = getline(&line2, &len2, fp2)) != -1) {
if (!strcmp(line, line2)) {
printf("Retrieved diff on line %zu :\n", read);
printf("%s", line);
}
}
if (ch1 == ch2)
printf("Files are identical \n");
else if (ch1 != ch2)
printf("Files are Not identical \n");
fclose(fp1);
fclose(fp2);
}
return (0);
}
You already have a very good answer (and always will from chux), but here is a slightly different approach to the problem. It uses automatic storage to reading file2 into an array of strings and then compares each line in file1 against every line in file2 to determine whether it is unique. You can easily convert the code to dynamically allocate memory, but for sake of complexity that was omitted:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { MAXC = 256, MAXL = 512 };
void file1infile2 (FILE *fp2, FILE *fp1, size_t *n2, size_t *n1);
int main (int argc, char **argv) {
FILE *fp1 = fopen (argc > 1 ? argv[1] : "file1.txt", "r");
FILE *fp2 = fopen (argc > 2 ? argv[2] : "file2.txt", "r");
size_t n1 = 0, n2 = 0;
if (!fp1 || !fp2) {
fprintf (stderr, "error: file open failed.\n");
return 1;
}
printf ("\nunique words in file1, not in file 2.\n\n");
file1infile2 (fp2, fp1, &n2, &n1);
printf ("\nanalyzed %zu lines in file1 against %zu lines in file2.\n\n",
n1, n2);
return 0;
}
void file1infile2 (FILE *fp2, FILE *fp1, size_t *n2, size_t *n1)
{
char buf[MAXC] = "";
char f2buf[MAXL][MAXC] = { "" };
size_t i;
*n1 = *n2 = 0;
while (*n2 < MAXL && fgets (buf, MAXC, fp2)) {
char *np = 0;
if (!(np = strchr (buf, '\n'))) {
fprintf (stderr, "error: line exceeds MAXC chars.\n");
exit (EXIT_FAILURE);
}
*np = 0;
strcpy (f2buf[(*n2)++], buf);
}
while (*n1 < MAXL && fgets (buf, MAXC, fp1)) {
char *np = 0;
if (!(np = strchr (buf, '\n'))) {
fprintf (stderr, "error: line exceeds MAXC chars.\n");
exit (EXIT_FAILURE);
}
*np = 0, (*n1)++;
for (i = 0; i < *n2; i++)
if (!(strcmp (f2buf[i], buf)))
goto matched;
printf (" %s\n", buf);
matched:;
}
}
Look over the code and let me know if you have any questions.
Example Use/Output
$ ./bin/f1inf2 dat/f1 dat/f2
unique words in file1, not in file 2.
john
the new
guy
analyzed 4 lines in file1 against 6 lines in file2.

Reading a file word by word with no ending chars

I have this small program in C that reads through a file a compares word by word,
how can I assure that words like "this," won't be read as a word? I would like it to read as "this"
int main(int argc, char *argv[]) {
if(argc != 3)
{
printf("Usage: ./sw <word> <filename> \n");
exit(1);
}
char* word = argv[1];
const char* filename = argv[2];
FILE* file = fopen(filename, "r");
if(file == NULL)
{
printf("Could not open file\n");
exit(1);
}
//Assuming one word can not have more than 250 chars
char w[250], check_eof;
do
{
check_eof = fscanf(file, "%s", w);
if(strcmp(word, w) == 0)
{
printf("W : %s \n", w);
}
} while(check_eof != EOF);
fclose(file);
return 0;
}
You can check if a char belongs to a word like this
int c = fgetc(file);
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
// c belongs to a word
word[n++] = c;
} else {
// end of word
if (strncmp(word, w, n) == 0) {
// word and w match!
}
}
If you #include <ctype.h>, then you can call isalpha(c) instead to test it.
In the code below, I use isalpha() and I copy the result string in a new buffer named res. However, this procedure can be done in-place, but I'll leave now for the sake of simplicity.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> // for isalpha()
int main(int argc, char *argv[]) {
char* word = "this";
const char* filename = "test.txt";
FILE* file = fopen(filename, "r");
if(file == NULL)
{
printf("Could not open file\n");
exit(1);
}
//Assuming one word can not have more than 250 chars
// ATTENTION, it is 249 chars, do NOT forget of the null terminator
char w[250], res[250];
int check_eof; // should be of type int, for EOF checking
do
{
check_eof = fscanf(file, "%s", w);
// what if 'word' appears as the last word
// in the file? You should check for eof
// right after fscanf()
if(check_eof == EOF)
break;
int i = 0, j = 0;
while (w[i]) // parse what we read
{
if (isalpha(w[i]))
res[j++] = w[i]; // keep only the alphabetic chars
i++;
}
res[j] = '\0'; // it should be a null terminated string
if(strcmp(word, res) == 0) // compare to 'res' now
{
printf("W : %s \n", res);
}
} while(1); // the terminating step is inside the body now
fclose(file);
return 0;
}

Resources