-4

enter image description here

This is main.c

enter image description here

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.

J...S
  • 5,079
  • 1
  • 20
  • 35
Huitseize
  • 1
  • 3
  • 1
    Compile with all warnings and debug info: `gcc -Wall -Wextra -g`. Then use the debugger `gdb`; your fix-my-code question is off-topic. Read about every standard function you are using: [fopen(3)](http://man7.org/linux/man-pages/man3/fopen.3.html) -and many other functions- can fail. Test that it does not like [here](https://stackoverflow.com/a/18193383/841108) – Basile Starynkevitch Oct 06 '17 at 17:49
  • 1
    Posting the text instead of images of it would've been better. – J...S Oct 06 '17 at 17:56
  • 2
    For one thing, you open the file twice without closing it in between. – Lee Daniel Crocker Oct 06 '17 at 18:02

1 Answers1

1

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.

J...S
  • 5,079
  • 1
  • 20
  • 35
  • I am poor at English and C programming yet. I understood your comment many things but, I didn't understand just one thing about fclose()... If you are okay, Can you teach me where I should use fclose() in my code...? – Huitseize Oct 06 '17 at 18:34
  • @Huitseize As soon as you are finished using a file. If you still need the file but need to open another, use a _different_ file pointer to open it. – J...S Oct 06 '17 at 18:39
  • @Huitseize If you remove the second `fopen()` in `main()`, your usage of `fclose()` seems appropriate. – J...S Oct 06 '17 at 18:40