8. File Contents

Introduction

Reading Lines with Continuation Characters

Counting Lines (or Paragraphs or Records) in a File

//------------------------------------------------------------------
/*
  using external program : wc -l
*/
#include <stdio.h>
#include <stdlib.h> // system(), exit(); malloc(), free()
#include <string.h> // strlen()
#include <errno.h> // errno

...

char file[100] = argv[1]; // a pathname
char * command;

// we format the shell command
command = malloc( (strlen("wc -l ") + 1) + (strlen(file) + 1) );
sprintf(command, "%s %s", "wc -l", argv[1]);

// bad solution

system(command);

// good solution : using popen() instead of system()

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);

...

//------------------------------------------------------------------
/*
    using standard C library
*/
#include <stdio.h>

...

char file[100] = argv[1]; // a pathname
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);

...

//------------------------------------------------------------------
/*
    using system calls
    /!\ fast implementation, the whole file is in memory
*/
#include <stdio.h>
#include <stdlib.h>

#include <fcntl.h> // open()
#include <sys/stat.h> 
#include <sys/types.h>
#include <unistd.h> // lseek(), close()

...

char file[100] = argv[1]; // a pathname
int fd;

fd = open(file, O_RDONLY);

size_t size;

size = lseek(fd, 0, SEEK_END ); // size of the buffer
  
char * buffer;
buffer = malloc(size);
  
lseek(fd, 0, SEEK_SET); // back to the beginning of the file

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 );

...

Processing Every Word in a File

Reading a File Backwards by Line or Paragraph

Trailing a Growing File

Picking a Random Line from a File

Randomizing All Lines

Reading a Particular Line in a File

Processing Variable-Length Text Fields

Removing the Last Line of a File

Processing Binary Files

Using Random-Access I/O

Updating a Random-Access File

Reading a String from a Binary File

Reading Fixed-Length Records

Reading Configuration Files

Testing a File for Trustworthiness

Program: tailwtmp

Program: tctee

Program: laston