I've got a very large text file that I'm trying to do word analysis on. Among word count, I might be looking for other information as well, but I left that out for simplicity.
In this text file I have blocks of text separated by asterisks '*'. The code I have below scans the text file and prints out # of characters and words as it should, but I'd like to reset the counter after an asterisk is met, and store all information in a table of some sort. I'm not so worried on how I'll make the table as much as I am unsure of how to loop the same counting code for each text block between asterisks.
Maybe a for loop like
for (arr = strstr(arr, "*"); arr; arr = strstr(arr + strlen("*"), "*"))
Example text file:
=-=-=-=-=-=-=-=-=-=-=-=-=-=-
I have a sentence. I have two sentences now.
*
I have another sentence. And another.
*
I'd like to count the amount of words and characters from the asterisk above this
one until the next asterkisk, not including the count from the last one.
*
...
...
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(EOF)
Desired output:
*# #words #alphaChar
----------------------------
1 9 34
-----------------------------
2 5 30
-----------------------------
3 28 124
...
...
I have tried
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int characterCount=0;
int counterPosition, wordCount=0, alphaCount=0;
//input file
FILE *file= fopen("test.txt", "r");
if (file== NULL)
printf("Cannot find the file.\n");
//Count total number of characters in file
while (1)
{
counterPosition = fgetc(speechFile);
if (counterPosition == EOF)
break;
++characterCount;
}
rewind(file); // Sends the pointer to the beginning of the file
//Dynamically allocate since array size cant be variable
char *arr= ( char*) malloc(totalCharacterCount);
while(fscanf(speechFile, "%c", &arr[i]) != EOF ) //Scan until the end of file.
i++; //increment, storing each character in a unique position
for(i = 0; i <characterCount; i++)
{
if(arr[i] == ' ') //count words
wordCount++;
if(isalpha(arr[i])) //count letters only
alphaCount++;
}//end for loop
printf("word count is %d and alpha count is %d", wordCount,alphaCount);
}
Since you are having full files text in array arr[], you need to divide that string arr using * as delimiter. you can use strtok() to divide that string using * as delimiter. Then perform the word count and character count operation on each token. read this link to know about strtok.
Related
I am trying to do the following the C programming language, any help or if you can finish the code I will be greatly appreciated:
I am trying to write a program in C programming language that uses file io, that will parse through the words using sscanf function and output each word in all the sentences inside a txt document (bar.txt). Here is the instructions.
Write a program that opens the file bar.txt name the program "reader". Pass a parameter to indicate lines to read. Read all the lines in the file based on the parameter 'lines' into a buffer and using sscanf parse all the words of the sentences into different string* variables. Print each of the words to the screen followed by a carriage return. You can hardwire filename (path of bar.xt) or use option to enter filename.
This is the txt file (bar.txt) i am working with:
bar.txt
this is the first sentence
this is the 2nd sentence
this is the 3rd sentence
this is the 4th sentence
this is the 5th sentence
end of file: bar.txt
usage of argv: Usage: updater [-f "filename"] 'lines'
-f is optional (if not provided have a hardwired name from previous program 2 (bar.txt))
'lines' integer from 1 to 10 (remember the files has 5-10 strings from previous program)
a sample input example for the input into the program is:
./reader -f bar.txt 1
OUTPUT:
Opening file "bar.txt"
File Sentence 1 word 1 = this
File Sentence 1 word 2 = is
File Sentence 1 word 3 = the
File Sentence 1 word 4 = first
File Sentence 1 word 5 = sentence
another example
./reader -f bar.txt 5
OUTPUT:
File Sentence 5 word 1 = this
File Sentence 5 word 2 = is
File Sentence 5 word 3 = the
File Sentence 5 word 4 = 5th
File Sentence 5 word 5 = sentence
Examples of commands:
./reader -f bar.txt 5
./reader -f bar.txt 2
./reader -f bar.txt 7
./reader 2
./reader 5
./reader 8
./reader 11
this is the code that I have so far please fix the code to show the desired output:
#include <stdlib.h>
#include <stdio.h>
#define MAXCHAR 1000
int main(int argc, char *argv[]) {
FILE *file;
char string[MAXCHAR];
char* filename = "c:\\cprogram\\fileio-activity\\bar.txt";
int integer = argv[3][0] - 48;
int i; //for loops
if (argv[1][0] == '-' && argv[1][1] == 'f')
{
file = fopen(filename, "r");
if (file == NULL){
printf("Could not open file %s",filename);
return 1;
}
while (fgets(string, MAXCHAR, file) != NULL)
printf("%s", string);
fclose(file);
return 0;
}
}
You need to get the filename from argv if they use the -f option. And you need to get the number of lines from a different argument depending on whether this option was supplied.
Use strcmp() to compare strings, rather than testing each character separately. And use atoi() to convert the lines argument to an integer, since your method only works for single-digit numbers.
#include <stdlib.h>
#include <stdio.h>
#define MAXCHAR 1000
function usage() {
fprintf(stderr, "Usage: reader [-f filename] lines\n");
exit(1);
}
int main(int argc, char *argv[]) {
FILE *file;
char string[MAXCHAR];
char* filename = "c:\\cprogram\\fileio-activity\\bar.txt";
int integer;
int i; //for loops
if (argc < 2) {
usage();
}
# Process arguments
if (strcmp(argv[1], "-f") == 0)
{
if (argc < 4) {
usage();
}
filename = argv[2];
integer = atoi(argv[3]);
} else {
integer = atoi(argc[1]);
}
file = fopen(filename, "r");
if (file == NULL){
fprintf(stderr, "Could not open file %s\n",filename);
return 1;
}
while (fgets(string, MAXCHAR, file) != NULL)
printf("%s", string);
fclose(file);
return 0;
}
To add to what Barmar already answered, for the further steps in completing the assignment:
Splitting a string into separate words is usually called tokenization, and we normally use strtok() for this. There are several ways how one can use sscanf() to do it. For example:
Use sscanf(string, "%s %s %s", word1, word2, word3) with however many word buffers you might need. (If you use e.g. char word1[100], then use %99s, to avoid buffer overrun bugs. One character must be reserved for the end-of-string character \0.)
The return value of sscanf() tells you how many words it copied to the word buffers. However, if string contains more than the number of words you specified, the extra ones are lost.
If the exercise specifies the maximum length of strings, say N, then you know there can be at most N/2+1 words, each of maximum length N, because each consecutive pair of words must be separated by at least one space or other whitespace character.
Use sscanf(string + off, " %s%n", word, &len) to obtain each word in a loop. It will return 1 (with int len set to a positive number) for each new word, and 0 or EOF when string starting at off does not contain any more words.
The idea is that for each new word, you increment off by len, thus examining the rest of string in each iteration.
Use sscanf(string + off, " %n%*s%n", &start, &end) with int start, end to obtain the range of positions containing the next word. Set start = -1 and end = -1 before the call, and repeat as long as end > start after the call. Advance to next word by adding end to off.
The beginning of the next word (when start >= 0) is then string + start, and it has end - start characters.
To "emulate" strtok() behaviour, one can temporarily save the terminating character (which can be whitespace or the end of string character) by using e.g. char saved = string[off + end];, then replace it with an end-of-string character, string[off + end] = '\0';, so that (string + start) is a pointer to the word, just like strtok() returns. Before the next scan, one does string[off + end] = saved; to restore the saved character, and off += end; to advance to the next word.
The first one is the easiest, but is the least useful in practical programs. (It works fine, but we do not usually know beforehand the string length and word count limitations.)
The second one is very useful when you have alternate patterns you can try for the next "word" or item; for example, when reading 2D or 3D vectors (points in a plane, or in three-dimensional space), you can support multiple different formats from <1 2 3> to [1,2,3] to 1 2 3, by trying to parse the most complicated/longest first, and trying the next one, until one of them works. (If none of them work, then the input is in error, of course.)
The third one is most useful in that it describes essentially how strtok() works, and what its side effects are. (It's saved character is hidden internally as a static variable.)
I would like to read in a text file and store the characters in an array. But the stored characters all have to be lower cased and keep a running count of the number of words. We can assume that we will use no more that the first 5000 words in the test and no more than the first 15 characters in a word. How would I fix make the each character into lower case.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *inFile;
char userInputFileName[100];
char *line = malloc(sizeof(char)*100);
int count = 0;
char *token;
char delim[] = " ,.!;:\n";
char *eachWord;
printf("Please enter the name of the text file \n");
scanf("%s", &userInputFileName);
inFile = fopen(userInputFileName, "r");
if(inFile == NULL)
{
fprintf(stderr, "Failed to open file \n");
exit(1);
}
while(fgets(line, sizeof(line),inFile)
{
printf("%s\n", line);
char newWord[5000];
while((eachWord = strtok(token, delim)) != NULL)
{
strcpy(newWord[count], eachWord);
}
count++;
}
}
Your while loop has some thought errors. I'll outline them to you but won't fix them so you can fix them and learn.
You write while(fgets(line, sizeof(line),... but that will read only 4 or 8 characters. Why? Read about sizeof and then look at what you are asking the size of.
In the while loop you say char newWord[5000]. That means you are allocating one array of 5000 characters. But in your problem statement you say "...5000 words in the test and no more than the first 15 characters". So there is a thought error and you would need an array for 5000 words of 15 characters each.
But, you are declaring this array in the loop, meaning it will be destroyed at the bottom of the while loop and recreated at the top. So you loose the word(s) just read and stored. You should allocate the array where it will not be destroyed and recreated with every iteration.
In tyour strcpy you do not make sure that only the first 15 characters (as per your problem statement) are copied. Use the right copy function to do that. And don't forget to terminate the copied characters.
And then after the while strtok... you increment count. That does not seem the right place to count the number of words.
Go back to the drawing board...
How do i read some 5 to 10 characters from a sample txt file using an fread funtion.
I have the following code:
#include <stdio.h>
main()
{
char ch,fname[20];
FILE *fp;
printf("enter the name of the file:\t");
gets(fname);
fp=fopen(fname,"r");
while(fread(&ch,1,1,fp)!=0)
fwrite(&ch,1,1,stdout);
fclose(fp);
}
when i enter any sample filename..it prints all the data of the file.
my question is how to print only the first 5 to 10 characters from the sample file.
Your while loop runs until read reaches the end of the file (reads 0 bytes for the first time).
You will want to change the condition by using a for loop or a counter.
i.e. (these are suggestions, not the full working code):
int counter = 10;
while(fread(&ch,1,1,fp)!=0 && --counter)
fwrite(&ch,1,1,stdout);
or
int i;
for(i=0; i < 10 && fread(&ch,1,1,fp) > 0 ; i++)
fwrite(&ch,1,1,stdout);
Good luck!
P.S.
To answer your question in the comments, fread allows us to read the data in "atomic units", so that if a whole unit isn't available, no data will be read.
A single byte is the smallest unit (1), and you are reading one unite (of a single byte), this is the 1,1 part in the fread(&ch,1,1,fp).
You could read 10 units using fread(&ch,1,10,fp) or read all the bytes unrequited for a single binary int (this won't be portable - it's just a demo) using int i; fread(&i,sizeof(int),1,fp);
read more here.
Here is a modified version of your code. Check the comments at the lines that are modified
#include <stdio.h>
#define N_CHARS 10 // define the desired buffer size once for code maintenability
int main() // main function should return int
{
char ch[N_CHARS + 1], fname[20]; // create a buffer with enough size for N_CHARS chars and the null terminating char
FILE *fp;
printf("enter the name of the file:\t");
scanf("%20s", fname); // get a string with max 20 chars from stdin
fp=fopen(fname,"r");
if (fread(ch,1,N_CHARS,fp)==N_CHARS) { // check that the desired number of chars was read
ch[N_CHARS] = '\0'; // null terminate before printing
puts(ch); // print a string to stdout and a line feed after
}
fclose(fp);
}
I am trying to mess around with file input in C, mainly with integer values in a matrix format. For instance, if I have a file like...
4 5 7 3
6 8 5 2
5 7 3 4
9 4 8 7
I am confused as to what the EOF command will do. I know I can use it to check for end of file, but what if I wanted to test the end of a row? What if I wanted to print the diagonal right to left ( so 3,5,7,9 ). I know I would have to go row by row, set a counter that counts at each iteration to find the length of the rows, print out the last value of that row, then deduct the pointer by 1 and go onto the next row. But how can I do this? As in, is EOF only for the file as a whole, or is there a C command that can more directly define row lengths and such.
A typical C program that reads multiple lines would look something like this:
char line[MAX_LINE_SIZE];
while (fgets(line, sizeof(line), inputFile) != NULL)
{
/* Do something with line */
}
The part that says "Do something with line" is where you should do something. One thing to do in your case would be to parse the line, and get one of the numbers in it. Which one would depend on the line number (which you have to keep track of your self), so the first number for the first line, the second number for the second line, etc. Then when you have all numbers (i.e. when the loop ends) you do what you want with the data.
After the loop ends, you can use feof or ferror to see if it ended because of end-of-file or an error.
When scanning through a file, you can separate the file into lines by splitting the file on the \n token. This is a newline and is present at the end of every line. Also, you can split on the \t token. This represents a tab.
#include <stdio.h>
#include <ctype.h>
#define MAX_DIGIT_OFLINE 10
#define EOR '\n' //END OF ROW
int main(){
char digits[MAX_DIGIT_OFLINE];
FILE *fp;
fp = fopen("data.txt", "r");
int n=0,last=-1;
for(;;){
int ch = fgetc(fp);
if(isdigit(ch)){
digits[n++] = ch;
} else if(ch == EOR || ch == EOF){
last = (last==-1) ? n -1: last -1;
putchar(digits[last]);
if(ch == EOF) break;
n = 0;
}
}
fclose(fp);
putchar(EOR);
return 0;
}
Let's say I'm reading in numbers from a text file. The text file consists of one-hundred fifty digit numbers (those are separate, there are 100 instances of 50 digit numbers).
I wanted to save each number as a row of a 2D array. To do this, I declared an array
char input[99][50] //50 columns to utilize the newlines in the text file
But it wouldn't read in the entire text file, even though, it seemed to me, it was the right size. It read in through the 99th number. For the 100th line, it printed a newline then a bunch of garbage symbols, etc. Please see the following:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//Set up the use of the input text file
FILE * ifp;
ifp = fopen("input.txt", "r");
//Declare variables
char input[100][50]; //Array to hold the input numbers
int i, j; //Variables to work with loops
//Begin by reading in the input file as characters,
//otherwise fscanf will take each entire line as
//a single number
for (i = 0; i <= 99; i++)
{
printf("%d)", i);
for (j = 0; j <= 50; j++)
{
fscanf(ifp, "%c", &input[i][j]);
printf("%c", input[i][j]);
}
}
system("pause");
return 0;
}
This will print it correctly. The thing that seems weird to me, is that it doesn't actually need to use that extra row that solves the problem...fscanf still only functions for the same range as before (0-99).
So...why does the array need to be [100]x[50]? Why does [99]x[50] cause so many issues?
Also, I added a newline to the last line of the text file because if I didn't, instead of a newline it printed an apostrophe ' to the screen at the end of the last line. Is this the symbol for some sort of end of file character?
Thanks in advance!
By the way, if you're interested in compiling this and seeing it happen, here's the text file input.txt:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
So...why does the array need to be [100]x[50]? Why does [99]x[50]
cause so many issues?
100 is the size you allocate, the indices go from 0 to 99 (99 + 1 = 100 ).
When you only allocate 99 you're missing the last line.
Since you're using a C string to handle the fifty digits, you have to get 1 extra char to terminate the string.
char input[100][51];
for (int i = 0; i != 100; ++i) /* 100 entries */
{
/* read your 50 digits normally here */
input[i][50] = '\0'; /* remember to terminate the string */
}