230 likes | 372 Views
GAME203 – C Files. stdio.h C standard Input/Output “getchar()” “putchar(key)” EOF Redirection using “>” Redirection using “<”. Redirection. Available in all OS's including DOS, Linux, Windows, MacOS Command line based “>” used to redirect output into a file (or device)
E N D
GAME203 – C Files • stdio.h C standard Input/Output • “getchar()” • “putchar(key)” • EOF • Redirection using “>” • Redirection using “<”
Redirection • Available in all OS's including DOS, Linux, Windows, MacOS • Command line based • “>” used to redirect output into a file (or device) • “<” used to redirect input from a file (or device)
Advantages of Redirection • No need for complicated code to choose file • Can be run in a very flexible way using command line scripts • Can replace user input with input from a file
Disadvantages of Redirection • Need command line (or equivalent) • Requires users that run the program to knopw about redirection
FILTER • One of the most powerful little programs EVER • You can • Echo • Substitute characters • Double-space info • Single-space info • etc.....
Using PIPES (in Linux/MacOS) • You can run this program that pipes (prints) the 2011 calendar out to the printer (lpr) device.$ cal 2011 | lpr where | is the PIPE symbol • You can pipe it to “more” to direct it to screen$ cal 2011 | more • The output of one program is the input of another program
FILES/DEVICES • UNIX (& Linux/MacOS) allow for files and devices to look like the same thing • /dev/ttyS0 or /dev/input/ttyS0 look like files but are really devices • “ls -l” in a directory of devices (such as “/dev”) will show 2 types of devices (at least)CHARACTER and BLOCK
Programming with Devices • Some devices are easy to access such as • Standard input • Standard output • They have built-in functions to work with them • “getchar( )” • “putchar( key )” • printf(“Hello World\n”);
Intro to File Handling • One portable technique of working with files is using FILE POINTERS • Use FILE *fp; // Create a pointer to a FILE struct fp = fopen( filename, filemode); // Opens a file as requested by // filemode
FILE MODE • It can be: • "r" Open a file for reading. The file must exist. • "w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. • "a"Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. • "r+" Open a file for update both reading and writing. The file must exist. • "w+" Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. • "a+" Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.
FILE NAMES • Use string specifying either • Absolute (specified from root “/”) • Relative (specified from where you currently are) • From home (specified from your home directory “~”)
Result of “fopen” • Returns a POINTER • NULL if it failed to open • Pointer to a FILE struct if it succeeded • Pointer is useful to allow subsequent operations to work! • You must check to see it is valid before trying to perform other operations
File Open Example /* fopen example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } return 0; }
getc int getc ( FILE * stream ); Get character from stream Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character. getc is equivalent to fgetc and also expects a stream as parameter, but getc may be implemented as a macro, so the argument passed to it should not be an expression with potential side effects. See getchar for a similar function without stream parameter.
putc int putc ( int character, FILE * stream ); Write character to stream Writes a character to the stream and advances the position indicator. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character. putc is equivalent to fputc and also expects a stream as parameter, but putc may be implemented as a macro, so the argument passed should not be an expression with potential side effects. See putchar for a similar function without stream parameter. Return Value If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.
fgets char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string. Return Value On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned. Use either ferror or feof to check whether an error happened or the End-of-File was reached.
fgets Example /* fgets example */ #include <stdio.h> int main() { FILE * pFile; char mystring [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { fgets (mystring , 100 , pFile); puts (mystring); fclose (pFile); } return 0; }
fputs int fputs ( const char * str, FILE * stream ); Write string to stream Writes the string pointed by str to the stream. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This final null-character is not copied to the stream. Return Value On success, a non-negative value is returned. On error, the function returns EOF.
fputs example /* fputs example */ #include <stdio.h> int main () { FILE * pFile; char sentence [256]; printf ("Enter sentence to append: "); fgets (sentence,255,stdin); pFile = fopen ("mylog.txt","a"); fputs (sentence,pFile); fclose (pFile); return 0; }
fprintf int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream Writes to the specified stream a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.
Standard Format Specifiers c Character d or i Signed decimal integer E Scientific notation (mantise/exponent) using e character E Scientific notation (mantise/exponent) using E character f Decimal floating point g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address
fscanf int fscanf ( FILE * stream, const char * format, ... ); Read formatted data from stream Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string. Return Value On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned.
Example of fscanf /* fscanf example */ #include <stdio.h> int main () { char str [80]; float f; FILE * pFile; pFile = fopen ("myfile.txt","w+"); fprintf (pFile, "%f %s", 3.1416, "PI"); rewind (pFile); fscanf (pFile, "%f", &f); fscanf (pFile, "%s", str); fclose (pFile); printf ("I have read: %f and %s \n",f,str); return 0; }