Basic file handling

Data structures

File operations use a file_info-structure defined as below:
struct file_info {
  char *name;
  FILE *fp;
  struct {
    unsigned int compressed : 1; /* is the file compressed */
    unsigned int pipe : 1;       /* the file is a pipe */
    unsigned int eof : 1;        /* has end of line been reached */
  } flags;
  int error;                     /* error code or 0 if OK */
  long lineno;                   /* line number we are on */
The fields of the structure are:
Used to store the file name
A FILE pointer to the file. You can use the fi2fp() macro to get the FILE pointer from the structure.
Error number or 0 if OK.
Line number of the current line. Updated when reading a file line by line with the getline function.
Currently defined flags are:
File is compressed. Implies that it is a pipe too.
The file is a pipe. Can be a compressed file, a piped command or standard input from/to a pipe.
True if end of file has been encountered. Reset when file is rewinded.


struct file_info *open_file(char *name, char *fmode);
int close_file(struct file_info *fi);
char *getline(struct file_info *fi);
struct file_info *open_file(char *name, char *fmode)
Open a file for reading or writing. If name is NULL or '-', uses standard input or output. Allowed characters in fmode are 'r' for reading, 'w' for writing, 'z' for compressed files and 'p' for piping output/input to/from a command (name is command string). 'p' and 'z' are not required in the fmode because they can be guessed from the filename: if the name and with the suffix .gz, .z or .Z the z-mode is assumed. If the name starts with the unix pipe character '|', the p-mode is assumed and the rest of the name is used as the command to be run.

If the file opening is successful, a pointer to a file_info-structure is returned. On error NULL is returned.

int close_file(struct file_info *fi)
Closes the file fi.

char *getline(struct file_info *fi)
Reads one line from file fi and returns a pointer to the line. The pointer returned points to a private buffer of the getline function so the next getline call will destroy the previous line. Make a copy of the line if you need it. Getline can handle lines of up to ABS_STR_LNG characters (defined in fileio.h or config.h).

Getline returns NULL when EOF is reached or an error occurs. The error and eof flags in fi are set accordingly.

int rewind_file(struct file_info *fi)
Goes to the beginning of file. If file is an ordinary file, seeks to the start of file. If the file is a compressed file, closes the old file and runs the uncompressing command again. Returns 0 on success, error code otherwise.

SOM/LVQ Programming info / SOM/LVQ Home Page / Neural Networks Research Centre