Reputation: 1255
I tried to make a program that tells you how many words, lines and characters are in a text file, but the function fopen()
fails to open the file. I tried both absolute and relative paths to the text file but I get the same output. Can you please tell me what's wrong?
My compiler is gcc version 4.6.3 (Linux)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 256
void tokenize(const char *filename)
{
FILE *f=NULL;
char line[N],*p;
unsigned long int ch=0,wd=0,ln=0;
int t;
f=fopen(filename,"rt");
if(f==NULL)
{
perror("The following error occurred");
exit(1);
}
fgets(line,N,f);
while(!feof(f))
{
ln++;
p=strtok(line," ");
while(p!=NULL)
{
wd++;
t=strlen(p);
ch+=t;
printf("Word number %lu with length %d: %s\n",wd,t,p);
p=strtok(NULL," ");
}
fgets(line,N,f);
}
printf("%lu lines, %lu words, %lu characters\n",ln,wd,ch);
fclose(f);
}
int main(void)
{
char filename[80];
size_t slen;
printf("Enter filename path:\n");
fgets(filename,80,stdin);
slen = strlen (filename);
if ((slen > 0) && (filename[slen-1] == '\n'))
filename[slen-1] = '\0';
printf("You have entered the following path: %s\n",filename);
tokenize(filename);
return 0;
}
output:
Enter filename path:
input.txt
You have entered the following path: input.txt
The following error occurred: No such file or directory
Upvotes: 0
Views: 3603
Reputation: 21
You can declare a function like:
void rmnewline(char *s)
{
int l=strlen(s);
if(l>0 && s[l-1]=='\n')
s[l-1]='\0';
}
and call it before using your char array.
Upvotes: 1
Reputation: 59607
You've retained the newline character from the input in your filename. You can see this when you echo the filename in your output: notice the blank line.
You'll need to strip off this newline before you pass it to your function. There are a few ways to do this, here's one:
size_t idx = strlen(filename);
if ((idx > 0) && filename[idx - 1] == '\n')
filename[idx - 1] = '\0';
Upvotes: 4
Reputation: 881323
You need to remove the trailing newline character from your string, with something like:
size_t slen = strlen (filename);
if ((slen > 0) && (filename[slen-1] == '\n'))
filename[slen-1] = '\0';
And, while I applaud your use of fgets
for user input (since it can be protected from buffer overflow), there's still a couple of edge cases you haven't considered, such as when the line is too long, or the user flags end of input). See here for a more robust solution.
Upvotes: 2