Sie sind auf Seite 1von 7

C file input/output

From Wikipedia, the free encyclopedia


Jump to: navigation, search The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header <stdio.h>. The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support for randomaccess data files; to read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream. The stream model of file I/O was popularized by the Unix operating system, which was developed concurrently with the C programming language itself. The vast majority of modern operating systems have inherited streams from Unix, and many languages in the C programming language family have inherited C's file I/O interface with few if any changes (for example, PHP). The C++ standard library reflects the "stream" concept in its syntax; see iostream.

Contents
[hide]

1 Opening a file using fopen 2 Closing a stream using fclose 3 Reading from a stream using fgetc o 3.1 The EOF pitfall 4 fwrite o 4.1 Writing a file using fwrite 5 Writing to a stream using fputc 6 Example usage 7 ftell 8 References 9 See also 10 External links

[edit] Opening a file using fopen


A file is opened using fopen, which returns an I/O stream attached to the specified file or other device from which reading and writing can be done. If the function fails, it returns a null pointer. The related C library function freopen performs the same operation after first closing any open stream associated with its parameters.

They are defined as


FILE *fopen(const char *path, const char *mode); FILE *freopen(const char *path, const char *mode, FILE *fp);

The fopen function is essentially a slightly higher-level wrapper for the open system call of Unix operating systems. In the same way, fclose is often a thin wrapper for the Unix system call close, and the C FILE structure itself often corresponds to a Unix file descriptor. In POSIX environments, the fdopen function can be used to initialize a FILE structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C. The mode parameter to fopen and freopen must be a string that begins with one of the following sequences: mode
r rb w a r+ w+ a+

description

open for reading open for writing (creates file if it doesn't exist). Deletes content and wb overwrites the file. ab open for appending (creates file if it doesn't exist) rb+ r+b open for reading and writing wb+ w+b open for reading and writing. Deletes content and overwrites the file. ab+ a+b open for reading and writing (append if file exists)

starts.. beginning beginning end beginning beginning end

The "b" stands for binary. The C standard provides for two kinds of files text files and binary files although operating systems are not required to distinguish between the two. A text file is a file consisting of text arranged in lines with some sort of distinguishing end-of-line character or sequence (in Unix, a bare line feed character; in Microsoft Windows, a carriage return followed by a line feed). When bytes are read in from a text file, an end-of-line sequence is usually mapped to a linefeed for ease in processing. When a text file is written to, a bare linefeed is mapped to the OS-specific end-of-line character sequence before writing. A binary file is a file where bytes are read in "raw", and delivered "raw", without any kind of mapping. When a file is opened with update mode ( '+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, writes cannot be followed by reads without an intervening call to fflush or to a file positioning function (fseek, fsetpos, or rewind), and reads cannot be followed by writes without an intervening call to a file positioning function.[1] Writing and appending modes will attempt to create a file of the given name, if no such file already exists. As mentioned above, if this operation fails, fopen will return NULL.

[edit] Closing a stream using fclose


The fclose function takes one argument: a pointer to the FILE structure of the stream to close.
int fclose(FILE *fp);

The function returns zero on success, or EOF on failure.

[edit] Reading from a stream using fgetc


The fgetc function is used to read a character from a stream.
int fgetc(FILE *fp);

If successful, fgetc returns the next byte or character from the stream (depending on whether the file is "binary" or "text", as discussed under fopen above). If unsuccessful, fgetc returns EOF. (The specific type of error can be determined by calling ferror or feof with the file pointer.) The standard macro getc, also defined in <stdio.h>, behaves in almost the same way as fgetc, except that being a macro it may evaluate its arguments more than once. The standard function getchar, also defined in <stdio.h>, takes no arguments, and is equivalent to getc(stdin).

[edit] The EOF pitfall


A common mistake when using fgetc, getc, or getchar is to assign the result to a variable of type char before comparing it to EOF. The following code fragments exhibit this mistake, and then show the correct approach: Mistake Correction

char c; int c; while ((c = getchar()) != EOF) while ((c = getchar()) != EOF) { { putchar(c); putchar(c); } }

Consider a system in which the type char is 8 bits wide, representing 256 different values. getchar may return any of the 256 possible characters, and it also may return EOF to indicate end-of-file, for a total of 257 different possible return values. When getchar's result is assigned to a char, which can represent only 256 different values, there is necessarily some loss of information when packing 257 items into 256 slots, there must be a collision. The EOF value, when converted to char, becomes indistinguishable from whichever one of the 256 characters shares its numerical value. If that character is found in the file, the above example may mistake it for an end-of-file indicator; or, just as bad, if type char is unsigned, then because EOF is negative, it can never be equal to any unsigned char, so the above example will not terminate at end-of-file. It will loop forever, repeatedly printing the character which results from converting EOF to char. On systems where int and char are the same size, even the "good" example will suffer from the indistinguishability of EOF and some character's value. The proper way to handle this situation is to check feof and ferror after getchar returns EOF. If feof indicates that end-offile has not been reached, and ferror indicates that no errors have occurred, then the EOF returned by getchar can be assumed to represent an actual character. These extra checks are rarely done, because most programmers assume that their code will never need to run on one of

these "big char" systems. Another way is to use a compile-time assertion to make sure that UINT_MAX > UCHAR_MAX, which at least prevents a program with such an assumption from compiling in such a system.

[edit] fwrite
In the C programming language, the fread and fwrite functions respectively provide the file operations of input and output. fread and fwrite are declared in <stdio.h>.

[edit] Writing a file using fwrite


fwrite is defined as
size_t fwrite (const void *array, size_t size, size_t count, FILE *stream);

function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.
fwrite

The function will return the number of elements written successfully. The return value will be equal to count if the write completes successfully. In case of a write error, the return value will be less than count. The following program opens a file named sample.txt, writes a string of characters to the file, then closes it.
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { FILE *fp; size_t count; const char *str = "hello\n"; fp = fopen("sample.txt", "w"); if(fp == NULL) { perror("failed to open sample.txt"); return EXIT_FAILURE; } count = fwrite(str, 1, strlen(str), fp); printf("Wrote %zu bytes. fclose(fp) %s.\n", count, fclose(fp) == 0 ? "succeeded" : "failed"); fclose(fp);//close de file return EXIT_SUCCESS; }

[edit] Writing to a stream using fputc


The fputc function is used to write a character to a stream.
int fputc(int c, FILE *fp);

The parameter c is silently converted to an unsigned char before being output. If successful, fputc returns the character written. If unsuccessful, fputc returns EOF. The standard macro putc, also defined in <stdio.h>, behaves in almost the same way as fputc, except that being a macro it may evaluate its arguments more than once. The standard function putchar, also defined in <stdio.h>, takes only the first argument, and is equivalent to putc(c, stdout) where c is that argument.

[edit] Example usage


The following C program opens a binary file called myfile, reads five bytes from it, and then closes the file.
#include <stdio.h> #include <stdlib.h> int main(void) { char buffer[5] = {0}; /* initialized to zeroes */ int i, rc; FILE *fp = fopen("myfile", "rb"); if (fp == NULL) { perror("Failed to open file \"myfile\""); return EXIT_FAILURE; } for (i = 0; (rc = getc(fp)) != EOF && i < 5; buffer[i++] = rc) ; fclose(fp); if (i == 5) { puts("The bytes read were..."); printf("%x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); } else fputs("There was an error reading the file.\n", stderr); return EXIT_SUCCESS; }

[edit] ftell
The function ftell returns the current offset in a stream in relation to the first byte.
ftell ( FILE * stream );

Commands for all of the above are found in the stdio.h header file.

Opening & Closing Files


The basic command used to open a file is:

FILE * fopen(char * filename, char * mode) The value returned is a handle to a file, defined in stdio.h, as FILE *. A null pointer is returned and can be tested for in case the call fails. So, the following is a good test for presence of a file: FILE * hFile; hFile = fopen( filename, "r"); if (hFile == NULL) { // Error, file not found } else { // Process & close file fclose(hFile); } The mode value in the above example is set to 'r', indicating that we want to read from the file. Other possible values are:
Ads by Google

Free Simulink CD Offer CD includes Simulink Demos, product info, reference examples and more.
www.mathworks.com

Flexible Screw Conveyors Replacement Spirals & Tubes for popular makes at competitive prices
www.trantec.info

w - write to the file, overwriting existing data a - append to an existing file r+ - read and write to a file

Using 'r+' means that all writing will take place at the end of the file, and that reading is sequential. The fclose function closes a valid file handle.

Reading & Writing Data


Once a file is open, we can read from it in one of two ways. We can use the standard printf functions for formatted output, or we can use the 'binary' file functions: int fread(void * buffer, int size, int num, FILE * hFile) int fwrite(void * buffer, int size, int num, FILE * hFile) Both of these can accept any variable that can be cast internally in the first parameter. Be aware, however, that if it is not a pointer type (int *, char * etc.), then it will need to be passed by reference (&nNumber, for example). This will create the appropriate cast to the variable being passed. So, to read a number, we would use:

int nRead = fread(&nNumber, sizeof(int), 1, hFile); In this example, we have provided the size of an integer (since we don't know the platform that we are compiling for), and a count of 1. This will cause the program to read the appropriate amount of data. We can also write the data back out using: int nWritten = fwrite(&nNumber, sizeof(int), 1, hFile); Of course, if we were to have a string that needed to be written to the file, so long as it is null terminated, we can use fwrite as follows: int nWritten = fwrite(szString, sizeof(char), strlen(szString), hFile); This will write out the string, but not the null terminator. Care, therefore, must be taken when using this function. If we want to read the data back in, without knowing the length of the string, we need to perform two operations for each file access: int nStrLen = strlen(szString); int nWritten = fwrite(&nStrLen, sizeof(int), 1, hFile); int nWritten = fwrite(szString, sizeof(char), nStrLen, hFile); We can then read the variable length string back in as follows: int nStrLen; int nRead = fread(&nStrLen, sizeof(int), 1, hFile); int nRead = fread(szString, sizeof(char), nStrLen, hFile); szString[nStrLen] = '\0'; // Append null terminator This trick can be used for any data types, including user defined data types, such as structs.

Deleting Files
The command to delete a file is: remove (char * szFileName); This will simply delete the file, with no way to get it back again without an external program. Read more: http://cprogramming.suite101.com/article.cfm/c_tutorial_file_handling_commands#ixzz0QX8P4zFX

Das könnte Ihnen auch gefallen