This is a kind of tricky question, different os use different
combinations to get the newline.
Windows: \r\n
Unix: \n
Mac: \r . it said to be, I have never used a Mac machine. However, the
text file transfered between M$'s os and Unix, I dit get some trouble
with the carriage return and line feed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
static const char *prog_name="wcn";
int
main(int argc, char *argv[]) {
FILE *fp;
int i;
if (argc == 1) {
printf("Usage: %s [files]\n", prog_name);
exit(EXIT_FAILURE);
}
for (i=1; i<argc; ++i) {
unsigned int r_c=0, n_c=0, rn_c=0;
int c, last=0;
if (! (fp=fopen(argv[i], "rb"))) {
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
continue;
}
while ((c=fgetc(fp)) != EOF) {
if (c == '\n') {
++n_c;
if (last == '\r')
++rn_c;
} else if (last == '\r')
++r_c;
last = c;
}
r_c += last=='\r'; /* In case the last char is '\r' */
if (ferror(fp)) {
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
if (fclose(fp) == EOF)
perror(prog_name);
continue;
}
if (fclose(fp) == EOF)
printf("%s: %s: %s\n", prog_name, argv[i], strerror(errno));
printf("%s:\t \\n: %u\t \\r: %u\t \\r\\n: %u\n", argv[i], n_c, r_c,
rn_c);
}
exit(EXIT_SUCCESS);
}
|