Input output da file

In stdio.h sono dichiarate alcune funzione che permettono di operare su file, alcune costanti ed un nuovo tipo dato, il tipo FILE; una variabile di tipo FILE è una variabile predisposta per contenere il descrittore di un file, cioè tutte le informazioni necessarie per gestire il file attraverso le varie funzioni di input-output, e il buffer, in cui vengono inseriti i dati letti dal file o quelli che devono essere inseriti nel file.

Per operare su un file è necessario inizializzare una variabile di tipo FILE con i dati relativi al file su cui vogliamo operare. Questa operazione viene effettuata dalla funzione fopen.

FILE *fopen( const char *filename, const char *mode );

filename nome del file da aprire

mode tipo di accesso permesso

The fopen function opens the file specified by filename. The character string mode specifies the type of access requested for the file, as follows:

"r" Opens for reading. If the file does not exist or cannot be found, the fopen call will fail.

"w" Opens an empty file for writing. If the given file exists, its contents are destroyed.

"a" Opens for writing at the end of the file (appending); creates the file first if it doesn't exist.

"r+" Opens for both reading and writing. (The file must exist.)

"w+" Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"a+" Opens for reading and appending; creates the file first if it doesn't exist.

When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. Although the file pointer can be repositioned using fseek or rewind, the file pointer is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

Return Value The fopen function returns a pointer to the open file. A null pointer value indicates an error.

Quando si è terminato di utilizzare un determinato file lo si rilascia, liberando le aree di memoria ad esso associato. Questa operazione viene effttuata dalla funzione fclose.

int fclose( FILE *stream );

stream Pointer to FILE structure

The fclose function closes stream. Tutti i buffers associati a stream sono svuotati prima della chiusura e i buffers sono rilasciati.

Return Value The fclose function returns 0 if the stream is successfully closed. return EOF to indicate an error.

In genere le operazioni che si devono compiere su di un file sono operazioni di input/output. Vediamone alcune.

int fgetc( FILE *stream );

stream Pointer to FILE structure

La funzione fgetc legge un singolo carattere a partire dalla posizione corrente del file associato a stream. Il carattere è convertito in un intero e viene restituito come tale. Infine la funzione incrementa il puntatore al file predisponendo il file stesso per la successiva operazione di input.

Return Value The fgetc function return the character read. Return EOF to indicate an error or end-of-file. Utilizzando feof o ferror è possibile distinguere tra un errore e la condizione di end of file.

char *fgets( char *string, int n, FILE *stream );

string Area di memoria in cui memorizzare i caratteri letti

n Massimo numero di caratteri da leggere

stream Pointer to FILE structure

The fgets function reads a string from the input stream argument and stores it in string. Characters are read from the current stream position up to and including the first newline character ('\n'), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first. The result is stored in string, and a null character ('\0') is appended. The newline character, if read, is included in the string. The fgets function is similar to the gets function; however, gets replaces the newline character with NULL.

Return Value If successful, the fgets function returns string. It returns NULL to indicate either an error or end-of-file condition. Use feof or ferror to determine whether an error occurred.

int fscanf( FILE *stream, const char *format [, argument ]... );

stream Pointer to FILE structure

format Format-control string

argument Optional arguments

The fscanf function reads data from the current position of stream into the locations given by argument (if any). Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format.

Return Value The fscanf function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned.

Return value is EOF for an error or end-of-file on stream before the first conversion.A return value of 0 means that no fields were assigned.

int fputc( int c, FILE *stream );

c Carattere da scrivere

stream Pointer to FILE structure

The fputc function writes the single character c to the output stream at the current position.

Return Value The fputc function return the character written. A return value of EOF indicates an error.

int fputs( const char *string, FILE *stream );

string Stringa da scrivere

stream Pointer to FILE structure

The fputs function copies string to the output stream at the current position. The terminating null character ('\0') is not copied.

Return Value The fputs function returns a nonnegative value if it is successful. If an error occurs, it returns EOF.

int fprintf( FILE *stream, const char *format [, argument ]... );

stream Pointer to FILE structure

format Format-control string

argument Optional arguments

The fprintf function formats and prints a series of characters and values to the output stream. Each argument (if any) is converted and output according to the corresponding format specification in format. The format argument has the same form and function that it does for the printf function; see the printf function for more information on format and argument.

Return Value The fprintf function returns the number of characters printed, or a negative value in the case of an output error.

int fseek( FILE *stream, long offset, int origin );

stream Pointer to FILE structure

offset Numero di bytes da origine

origin Posizione iniziale

La funzione fseek sposta il file pointer associato a stream alla nuova posizione che è offset bytes da origin. La successiva operazione su stream avverrà a partire dalla nuova posizione.

Il valore di origin può essere uno dei seguenti valori definiti in stdio.h.

SEEK_CUR Current position of file pointer

SEEK_END End of file

SEEK_SET Beginning of file

La funzione fseek viene utilizzata per riposizionare il file pointer in qualunque posizione del file. Il puntatore può essere posizionato anche oltre il fine file. In questo caso la funzione fseek rimuove il fine file per le operazioni successive che ovviamente non potranno essere di lettura.

Return Value If successful, fseek returns 0. Otherwise, it returns a nonzero value.

On devices incapable of seeking, the return value is undefined.

int fsetpos( FILE *stream, const fpos_t *pos );

stream Target stream

pos Position-indicator storage

The fsetpos function sets the file-position indicator for stream to the value of pos, which is obtained in a prior call to fgetpos against stream.

The function clears the end-of-file indicator and undoes any effects of the ungetc function on stream. After calling fsetpos, the next operation on stream may be either input or output.

Return Value If successful, the fsetpos function returns 0. On failure, the function returns a nonzero value and sets errno to one of the following manifest constants (defined in ERRNO.H):

EBADF The object that stream points to is not a valid file handle, or the file is not accessible.

EINVAL An invalid stream value was passed.

int fgetpos( FILE *stream, fpos_t *pos );

stream Target stream

pos Position-indicator storage

The fgetpos function gets the current value of the stream argument's file-position indicator and stores it in the object pointed to by pos. The fsetpos function can later use information stored in pos to reset the stream argument's pointer to its position at the time fgetpos was called. The pos value is stored in an internal format and is intended for use only by the fgetpos and fsetpos functions.

Return Value If successful, the fgetpos function returns 0. On failure, it returns a nonzero value and sets errno to one of the following manifest constants (defined in STDIO.H):

EBADF The specified stream is not a valid file handle or is not accessible.

EINVAL The stream value is invalid.

int feof( FILE *stream );

stream Pointer to FILE structure

The feof routine (implemented both as a function and as a macro) determines whether the end of stream has been reached. Once the end of the file is reached, read operations return an end-of-file indicator until the stream is closed or until rewind, fsetpos, fseek, or clearerr is called against it.

Return Value The feof function returns a nonzero value after the first read operation that attempts to read past the end of the file. It returns 0 if the current position is not end-of-file. There is no error return.

int fflush( FILE *stream );

stream Pointer to FILE structure

If the file associated with stream is open for output, fflush writes to that file the contents of the buffer associated with the stream. If the stream is open for input, fflush clears the contents of the buffer. Buffers are automatically flushed when they are full, when the stream is closed, or when a program terminates normally without closing the stream. Also, fflush(NULL) flushes all streams opened for output.

The stream remains open after the call. The fflush function has no effect on an unbuffered stream.

Return Value The fflush function returns the value 0 if the buffer was successfully flushed. The value 0 is also returned in cases in which the specified stream has no buffer or is open for reading only. A return value of EOF indicates an error.

Note If fflush returns EOF, data may have been lost because of a failed write.

When setting up a critical error handler, it is safest to turn buffering off with the setvbuf function or to use low-level I/O routines such as open, close, and write instead of the stream I/O functions.

size_t fread( void *buffer, size_t size, size_t count, FILE *stream );

buffer Storage location for data

size Item size in bytes

count Maximum number of items to be read

stream Pointer to FILE structure

The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage-return-line-feed pairs are replaced with single line-feed characters. The replacement has no effect on the file pointer or the return value.

The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined.

Return Value The fread function returns the number of full items actually read, which may be less than count if an error occurs or if the file end is encountered before reaching count.

The feof or ferror function should be used to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged.

size_t fwrite( const void *buffer, size_t size, size_t count, FILE * stream );

buffer Pointer to data to be written

size Item size in bytes

count Maximum number of items to be written

stream Pointer to FILE structure

The fwrite function writes up to count items, of length size each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written.

If stream is opened in text mode, each carriage return is replaced with a carriage-return-line-feed pair. The replacement has no effect on the return value.

Return Value The fwrite function returns the number of full items actually written,

which may be less than count if an error occurs. Also, if an error occurs, the file-position

indicator cannot be determined.

/* FREAD.C: This program opens a file named FREAD.OUT and

* writes 25 characters to the file. It then tries to open

* FREAD.OUT and read in 25 characters. If the attempt succeeds,

* the program displays the number of actual items read.

*/

#include <stdio.h>

void main( void )

{

FILE *stream;

char list[30];

int i, numread, numwritten;

/* Open file: */

if( (stream = fopen( "fread.out", "w+" )) != NULL )

{

for ( i = 0; i < 25; i++ )

list[i] = (char)('z' - i);

/* Write 25 characters to stream */

numwritten = fwrite( list, sizeof( char ), 25, stream );

printf( "Wrote %d items\n", numwritten );

fclose( stream );

}

else

printf( "Problem opening the file\n" );

if( (stream = fopen( "fread.out", "r+" )) != NULL )

{

/* Attempt to read in 25 characters */

numread = fread( list, sizeof( char ), 25, stream );

printf( "Number of items read = %d\n", numread );

printf( "Contents of buffer = %.25s\n", list );

fclose( stream );

}

else

printf( "Was not able to open the file\n" );

}