프로그래머의 삶 Programmer's Life/C & C++

입력파일의 word수, char수, line수 출력

Oliver's World 2008. 11. 3. 14:06
728x90
#include <fcntl.h>
#include <stdio.h>

long ch;
long word;
long line;

main(void)
{
FILE *ifp, *ofp;
char buffer[BUFSIZ];
int file, j, i;

ifp = fopen("input.txt", "r");
ofp = fopen("output.txt", "w");

if((file = open("input.txt", O_RDONLY)) < 0) {
perror("open error");
exit(1);
}
while( (j = read(file, buffer, BUFSIZ )) > 0 ) {
ch += j;
for(i=0 ; i < j ; i++) {
if( buffer[i]==' ' || buffer[i]=='\n') {
word++;
if(buffer[i] == '\n')
line++;
}
}
}
fprintf(ofp, "글자수 : %ld\n워드수 : %d\n라인수 : %d\n", ch, word, line);
fclose(ifp);
fclose(ofp);
}
728x90