#include <stdio.h>
#include <stdlib.h> #include <string.h> #include <errno.h>
...
char file[100] = argv[1]; char * command;
command = malloc( (strlen("wc -l ") + 1) + (strlen(file) + 1) );
sprintf(command, "%s %s", "wc -l", argv[1]);
system(command);
FILE * message;
if( (message = popen(command, "r")) == NULL ) {
fprintf(stderr, "error popen %d\n", errno);
exit(1);
}
char wc_output[100];
fgets(wc_output, sizeof wc_output, message);
fprintf(stdout, "%s", wc_output);
pclose(message);
free(command);
...
#include <stdio.h>
...
char file[100] = argv[1]; FILE * fp;
if( (fp = fopen( file, "r" )) == NULL ) {
perror("fopen");
exit(1);
}
int line = 0;
char ch;
while ( (ch = getc(fp)) != EOF )
if (ch == '\n')
line++;
fprintf(stdout, "number of lines : %d\n", line );
fclose(fp);
...
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> #include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
...
char file[100] = argv[1]; int fd;
fd = open(file, O_RDONLY);
size_t size;
size = lseek(fd, 0, SEEK_END );
char * buffer;
buffer = malloc(size);
lseek(fd, 0, SEEK_SET);
if( (read(fd, buffer, size)) != size ) {
perror("read");
exit(1);
}
close(fd);
int line = 0;
int i;
for( i = 0; i < size; i++ ) {
if(buffer[i] == '\n')
line++;
}
free(buffer);
fprintf(stdout, "number of lines : %d\n", line );
... |