- #1
pokkie
- 1
- 0
Homework Statement
Emulating the wc command in linuxOutput suppose to be like this :
[root@localhost home]# wc
This is a test
1 4 15
[root@localhost home]# ./wc1.exe
This is a test
1 4 15
[root@localhost home]# cat File1.dat
This is a test
[root@localhost home]# wc < File1.dat
1 4 15
[root@localhost home]# ./wc1.exe < File1.dat
1 4 15
[root@localhost home]#
Homework Equations
null
The Attempt at a Solution
Code:
#include <stdio.h>
#define MaxLine 200
char Line[MaxLine]; //one line from the file
int NChars = 0; //number of characters seen so far
int NWords = 0; //number of words seen so far
int NLines = 0; //number of lines seen so far
int LineLength; //length of the current line
int fromfile;
FILE *fp1;PrintLine() //for debugging purposes only
{
int I;
for(I=0; I < LineLength; I++) printf("%c",Line[I]);
printf("\n");
}
int WordCount() //count words{ int I,NBlanks =0;
for (I=0;I < LineLength; I++)
if (Line[I]== ' ') NBlanks++;
if(LineLength > 1) return NBlanks+1;
else return 0;
}
int ReadLine() //from user input
{
char C; int I;
//printf("please input something: ");
//scanf("%c",&C);
if (scanf("%c",&C) == -1) return 0;
Line[0]= C;
if (C =='\n') return 1;
for (I=1;;I++) {
scanf("%c",&C);
Line[I]=C;
if (C=='\n') return I+1;
}
}int ReadLine2() //from file{
char C; int I;
if (fscanf(fp1,"%c",&C) == -1) return 0;
Line[0]= C;
if (C =='\n') return 1;
for (I=1;;I++) {
scanf("%c",&C);
Line[I]=C;
if (C=='\n') return I+1;
}
}UpdateCounts()
{
NChars += LineLength;
NWords += WordCount();
NLines++;
}
main()
{
printresult();}
int printresult() {
while(1) {
LineLength = ReadLine();
if(LineLength ==0) break;
UpdateCounts();
}
printf("%7d%8d%7d\n",NLines,NWords,NChars);
if(!(fp1 = fopen("File1.DAT", "r")))
{
printf("Error opening FILE1.DAT for reading");
while((fromfile =fgetc(fp1)) !=EOF)
{
fromfile = ReadLine2();
if(fromfile ==0) break;
UpdateCounts();
}
printf("%3d%3d%3d\n",NLines,NWords,NChars);
fclose(fp1);
}
}
[root@localhost home]# wc
This is a test
1 4 15
[root@localhost home]# ./wc1.exe
This is a test
1 4 15
[root@localhost home]# cat File1.dat
This is a test
[root@localhost home]# wc < File1.dat
1 4 15
[root@localhost home]# ./wc1.exe <File1.dat
1 4 15
Segmentation faultHow do I get the .dat loop to run? =(
thank you.
Last edited: