I wrote a c program to count the number of time the word "printf" occurs in a specific file (here "document.c"). "document.c" has multiple lines of code. What I have done is I started with a while loop to iterate over every lines of the file and then I am reading the characters of each lines inside the for loop by using the function strstr.
It does not print anything with my current code. Moreove, I think there is some other minor issues because in an older version it used to print but not correctly, it printed a number much more larger than the actual number of "printf" in the document.
I am also novice in c.thank you!
int counter() {
FILE * filePointer;
filePointer = fopen("document.c", "r");
int counter = 0;
char singleLine[200];
while(!feof(filePointer)){
fgets(singleLine, 200, filePointer);
for (int i = 0; i < strlen(singleLine); i++){
if(strstr(singleLine, "printf")){
counter++;
}
}
}
fclose(filePointer);
printf("%d",counter);
return 0;
}
You're iterating over each character in the input line, and then asking if the string "printf" appears anywhere in the line. If the line contains 5 characters, you'll ask this 5 times; if it contains 40 characters, you'll ask this 40 times.
Assuming that you're trying to cover the case where "printf" can appear more than once on the line, look up what strstr() returns, and use that to adjust the starting position of the search in the inner loop (which shouldn't iterate over each character, but should loop while new "hits" are found).
(Note to up-voters: I'm answering the question, but not providing code because I don't want to do their homework for them.)
Related
Say you have a text file filled with sentences. For example:
hey how are you
you good?
nice to meet you jeff
I'm writing a program to print things out depending on how many indexes are on each line but I cant wrap my head around how to find how many words on each line. How could I go about counting how many words are on each line?
for (int i=0; i < wordle->leng; i++) {
printf ("%s ", wordle->allwords[i]);
This is my print function for the program. leng is how many lines so it knows how many times to repeat.
Some of the lines have 5 words, some 3, and it isn't printing in the correct format. Also not all lines will end with punctuation.
The POSIX getline() function is very useful for that; it reads line from stream until EOL. So you can read with that line by line and the you could make a loop that adds 1 to int word_count = 0; every time you read something that is not a whitespace and the previous char before that was whitespace (but you have to make additional logic for initial word).
You can use fgets() if you don't have getline() available, but it doesn't expand the buffer to deal with extra long lines, unlike getline().
I need to write a program in C, that prints out last five lines of file by using basic functions like open, read, write, close, lseek. My code so far:
int main(int argc, char *argv[]){
int fd1=open(argv[1], O_RDONLY);
char c;
int currPos = lseek(fd1,-2,SEEK_END);
while(currPos != -1){
read(fd1,&c,sizeof(c));
currPos--;
currPos=lseek(fd1,currPos,SEEK_SET);
if (c == '\n'){
}
}
return 0;
}
Can anybody help me? I think I need to store those characters in array and then print it backwards, but I don't know how.
Why not count the number of characters read while reading back to the fifth newline (call that n) and then do a read of n characters? You don't need to store the data, it's already stored in the file.
Inside the if statement you can count how many '\n' characters you encounter from the end of your file. When you encounter the 6th end-of-line, you know you are at the end of the 6-th-from-the-end line (assuming that the last line also contains an end-of-line character at the end) , so you just print from that point to the end of the file.
You do not need to save the characters in an array, since they are already saved in your file.
You can just do (after your while loop):
int i=read(fd1,&c,1);
while(i){
printf("%c",c);
i = read(fd1,&c,1);
}
It may not be the most efficient way to do it, but it should do the trick.
Note: There is no need to write sizeof(c), since c is a char, and chars are always 1 byte long.
Also, you should always check the return value of read, you never know when something goes wrong in your system and your program crashes because of a read gone wrong.
For a program I'm writing I need to read a file line by line and print out the longest line in the file, along with the length of that line as well as the total number of lines in the file.
I have this:
char line[100];
char* longLine;
int count, longestLine, temp;
count=0;
longestLine=0;
while(fgets(line,100,inFile) != NULL) {
temp=strlen(line);
if(temp > longestLine) {
longLine=line;
longestLine=temp;
}
count++;
}
printf("Longest line: %sLength of longest line: %d characters\nTotal number of lines: %d\n",longLine, longestLine, count);
longestLine and count print correctly, but no matter what, longLine always prints out the last line of the file instead of the longest line. Using print statements I've determined that the if statement in the while loop is only called when a new longest line is found, yet longLine gets changed regardless. Can anyone tell me what I'm doing wrong? Thanks!
The problem is that longLine is a pointer. You're going into the if and then setting longLine to point to line... which at the start of the next while has changed. What I suspect you intended to do was copy the contents of line into longLine using strcpy, otherwise, each time through the loop. longLine will always point to the currently evaluating line.
A footnote, your code is incorrect even if the code function correctly. You need to initialize longestLine to zero before it is used. Not all compilers may initialize it to zero - it might have garbage in it. Temp may never be larger than the garbage in longestLine.
I'm developing a program that will translate a string from the user (English) into Spanish.
For the assignment I'm given a file that contains a list of a 100 words and their spanish equivalent. I've successfully opened that file, and fed it to the string with a two dimensional array.
What I'm having difficulty with is parsing the words so it will allow me to find the equivalent version of the given words; any words that aren't given are suppose to be replaced with asterisks (*). Any ideas on how I can parse the words from the users inputted string?
Below is snippits of the source code to save some time.
--Thanks
char readFile[100][25];
fp = fopen("words.dat", "r");
if (fp == NULL){
printf ("File failed to load\n");
}
//This is how I stored the file into the two dimensional string.
while (fgets(readFile, 100, fp)){
x++;
}
printf ("User please input string\n");
gets (input);
That's as far as I've gotten. I commented out the for-loop that outputs the words so I can see the words (for the sake of curiousity) and it was successful. The format of the file string is
(english word), (spanish word).
First of, the array you declare is 100 arrays of 25-character arrays. If we talk about "lines" it means you have 100 lines where each line can be 24 characters (remember we need one extra for the terminating '\0' character). If you want 25 lines of 99 characters each, switch place of the sizes.
Secondly, you overwrite the same bytes of the array over and over again. And since each sub-array is actually only 25 characters, you can overwrite up to four of those arrays with that fgets call.
I suggest something like this instead:
size_t count = 0;
for (int i = 0; i < sizeof(readFile) / sizeof(readFile[0]) &&
fgets(readFile[i], sizeof(readFile[i]), fp); i++, count++)
{
}
This will make sure you don't read more than you can store, and automatically reads into the correct "line" in the array. After the loop count will contain the number of lines you read.
I'm learning C from K&R's "The C Programming Language" book. I'm doing the exercises specified in the book. I'm on exercise number 1.16, but I don't understand it.
Exercise 1.16:
Revise the main routine of the longest-line program so it will
correctly print the length of arbitrarily long input lines, and as
much as possible of the text.
My questions:
"...as much as possible of the text..." - is there some limitation on string length? Maybe in standard headers there's a variable with the max allowed value of string length?
"...the length of arbitrarily long input lines..." - but in the code MAXLINE is defined as 1000. It is limited size too. I see some solutions here, but in my opinion it is not solution decision, since on the former there is a restriction on length of a line (1000 characters).
Maybe I don't understood the task. My understanding is I must remove the 1000-character limitation.
It's a pretty early exercise in K&R, you're just supposed to do some minor changes to the code, not a total redesign of the code.
"...as much as possible of the text..."
is up to you to interpret. I'd do it by printing what's stored in the longest buffer. i.e. print out up to 1000 characters of the line. Again, it's an early exercise, with little introduction to dynamically allocated memory yet. And at the time K&R was written, storing away arbitrarily long text lines wasn't as feasible as it is today.
"...the length of arbitrarily long input lines..."
Is a hard requirement. You're supposed to find the correct length no matter how long it is (at least within the bounds of an int. )
One way to solve this problem is:
After the call to getline(), check if the last character read into the line buffer is a newline ('\n')
If it is, you read a complete line. The len variable is the correct length of the line(the return value of getline(), and no special consideration is needed compared to to original code.
If it is not , you did not read the entire line, and need to hunt for the end of this line. You add a while loop, calling getchar() until it returns a newline (or EOF), and count the number of characters you read in that loop. Just do len++ to count.
When the while loop is done, the new len is now the actual length of the line, but our buffer just has the first 999 characters of it.
As before, you store away (the copy() function call) the current line buffer (max 1000 chars) if this line is the longest so far.
When you're done, you print out the stored line as before (the longest buffer) and the max variable for the length.
Due to the above mentioned while loop that max length is now correct.
If the longest line indeed was longer than 1000 chars. you at least print out those first 999 chars - which is "as much as possible".
I'll not spoil it and post the code you need to accomplish this, but it is just 6 lines of code that you need to add to the longest-line program of exercise 1-16.
On modern machines "as much as possible of the text" is likely to be all of the text, thanks to automatically line-wrapping terminal programs. That book was written when teletype terminals were still in use. There is no limitation on string length other than perhaps memory limitations of the machine you're working on.
They're expecting you to add some kind of loop to read characters and look for newlines rather than assuming that a read into the MAXLINE sized buffer is going to contain a newline for sure.
here is my version:
int getline(char s[],int lim)
{
int c,i;
for(i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';++i)
s[i]=c;
if(c=='\n')
{
s[i]=c;
++i;
}
if(c!=EOF)
{
while((c=getchar())!=EOF&&c!='\n')
i++;
}
s[i]='\0';
return i;
}
#define MAXLINE 1000
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max=0;
while((len=getline(line,MAXLINE))>1)
{
if(len>max)
{
max=len;
copy(longest,line);
}
}
if(max>0)
{
printf("%d:%s",max,longest);
}
return 0;
for some unknown reasons ,the example code doesn't work in my pc
particularly,when the condition is 'len>0',the loop won't end
i think the main reason is that when you type nothing,but you still have to press enter,so it is received as '\n',and the len is 1;
i think it satisfy the requirement that print the length of arbitrarily long input lines, and as much as possible of the text.
And it works like this
#include
main()
{
long tlength = 0;
short input, llength = 1;
while (llength > 0) {
llength = 0;
while ((input = getchar()) != EOF) {
++llength;
if (input == '\n')
break;
}
tlength = tlength + llength;
printf("\nLength of just above line : %5d\n\n", llength);
}
printf("\n\tLength of entire text : %8ld\n", tlength);
return 0;
}
According to me, This question only wants the length of each arbitrarily line + At last the length of entire text.
Try to run this code and tell me is it correct according to question because i too confuse in this problem.
I want to offer that this exercise actually makes more sense if imagine that the limit of the number of characters you can copy is very small -- say, 100 characters -- and that your program is supposed to judge between lines that are longer than that limit.
(If you actually change the limit so that it's very small, the code becomes easier to test: if it picks out the first line that hits that small limit, you'll know your code isn't working, whereas if it returns the first however-many characters of the longest line, it's working.)
Keep the part of the code that copies and counts characters until it hits a newline or EOF or the line-size-limit. Add code that picks up where this counting and copying leaves off, and which will keep counting even after the copying has stopped, so long as getchar() still hasn't returned an EOF or a newline.
My solution: just below the call to getLine
if ( line[len-1] != '\n' && line[len-1] != EOF) //if end of line or file wasnt found after max length
{
int c;
while ( ( c = getchar() ) != '\n' && c != EOF )
len++; //keep counting length until end of line or file is found
}
to test it, change MAXLINE to 25