This is main.c
This is print.c
#include <stdio.h>
int wc(FILE *pointer)
{
int a;
int character=0,word=0,line=0;
a = getc(pointer);
while ( a != EOF )
{
character++;
if (a == ' ')
word++;
if (a == '\n')
line++;
a = getc(pointer);
}
printf("character: %4d, word: %4d, line: %4d \n", character,word,line);
return 0;
}
This is word.c
gcc -c print.c
gcc -c word.c
gcc -c main.c
gcc -o main main.o print.o word.o
./main
text.txt
text.txt
segmentation fault (core dumped)
This is compile ways that i used.
But I don't know why I have segmentation fault(core dumped).
Please help me.
In main()
, you should check if the fopen()
were successful by seeing if the return value is NULL
in which case an error occurred.
Also, you are using argv[1]
even if the condition argc>1
is not satisfied with the second fopen()
in main()
. argv[1]
won't be there if argc
is less than 2
.
In the while
loop in printfile()
, the break
statement would be executed on the first iteration itself.
So making that while
into an if
statement and removing the break
would have the same effect.
In the while
loop of wc()
,
if (a == ' ')
word++;
if (a == '\n')
line++;
could be made
if (a == ' ')
word++;
else if (a == '\n')
line++;
No need to check if a
is \n
if a
is (space).
Edit: And don't forget to close all the files you've opened once you are done using them.