#include #include /* --------------------------- size_t fread(void *ptr, size_t size, size_t n, FILE *stream); Description Reads data from a stream. fread reads n items of data each of length size bytes from the given input stream into a block pointed to by ptr. The total number of bytes read is (n * size). Return Value On success fread returns the number of items (not bytes) actually read. On end-of-file or error it returns a short count (possibly 0). --------------------------- size_t fwrite(const void *ptr, size_t size, size_t n, FILE *stream); Description Writes to a stream. fwrite appends n items of data each of length size bytes to the given output file. The data written begins at ptr. The total number of bytes written is (n x size). ptr in the declarations is a pointer to any object. Return Value On successful completion fwrite returns the number of items (not bytes) actually written. On error it returns a short count. --------------------------- FILE *fopen(const char *filename, const char *mode); Description Opens a stream. fopen opens the file named by filename and associates a stream with it. fopen returns a pointer to be used to identify the stream in subsequent operations. The mode string used in calls to fopen is one of the following values: Value Description r Open for reading only. w Create for writing. If a file by that name already exists, it will be overwritten. a Append; open for writing at end-of-file or create for writing if the file does not exist. r+ Open an existing file for update (reading and writing). w+ Create a new file for update (reading and writing). If a file by that name already exists, it will be overwritten. a+ Open for append; open (or create if the file does not exist) for update at the end of the file. --------------------------- int fseek(FILE *stream, long offset, int whence); Description Repositions a file pointer on a stream. fseek sets the file pointer associated with stream to a new position that is offset bytes from the file location given by whence. For text mode streams offset should be 0 or a value returned by ftell. whence must be one of the values 0. 1, or 2 which represent three symbolic constants (defined in stdio.h) as follows: Constant whence File location SEEK_SET 0 File beginning SEEK_CUR 1 Current file pointer position SEEK_END 2 End-of-file fseek discards any character pushed back using ungetc. fseek is used with stream I/O; for file handle I/O use lseek. After fseek the next operation on an update file can be either input or output. */ int main(void) { FILE *stream; char msg[] = "this is a test"; char buf[20]; if ((stream = fopen("dummy.file", "w+")) == NULL) { fprintf(stderr, "Cannot open output file.\n"); return 1; } /* write some data to the file */ fwrite(msg, strlen(msg)+1, 1, stream); /* seek to the beginning of the file */ fseek(stream, SEEK_SET, 0); /* read the data and display it */ fread(buf, strlen(msg)+1, 1, stream); printf("%s\n", buf); fclose(stream); return 0; }