game203 – c files stdio.h c standard input/output “getchar()” “putchar(key)” eof...

23
GAME203 – C Files stdio.h C standard Input/Output “getchar()” “putchar(key)” EOF Redirection using “>” Redirection using “<”

Upload: edwin-barnett

Post on 29-Dec-2015

244 views

Category:

Documents


0 download

TRANSCRIPT

  • GAME203 C Filesstdio.h C standard Input/Outputgetchar()putchar(key)EOFRedirection using >Redirection using
  • RedirectionAvailable in all OS's including DOS, Linux, Windows, MacOSCommand line based> used to redirect output into a file (or device)
  • Advantages of RedirectionNo need for complicated code to choose fileCan be run in a very flexible way using command line scriptsCan replace user input with input from a file

  • Disadvantages of RedirectionNeed command line (or equivalent)Requires users that run the program to knopw about redirection

  • FILTEROne of the most powerful little programs EVERYou canEchoSubstitute charactersDouble-space infoSingle-space infoetc.....

  • Using PIPES (in Linux/MacOS)You can run $ cal 2011 | lpr where | is the PIPE symbolYou can run $ cal 2011 | moreThe output of one program is the input of another program

  • FILES/DEVICESUNIX (& 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 devicesls -l in a directory of devices (such as /dev) will show 2 types of devices (at least) CHARACTER and BLOCK

  • Programming with DevicesSome devices are easy to access such asStandard inputStandard outputThey have built-in functions to work with themgetchar( )putchar( key )printf(Hello World\n);

  • Intro to File HandlingOne portable technique of working with files is using FILE POINTERSUse FILE *fp; // Create a pointer to a FILE struct fp = fopen( filename, filemode); // Opens a file as requested by // filemode

  • FILE MODEIt 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 NAMESUse string specifying eitherAbsolute (specified from root /)Relative (specified from where you currently are)From home (specified from your home directory ~)

  • Result of fopenReturns a POINTERNULL if it failed to openPointer to a FILE struct if it succeededPointer 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 int main (){ FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } return 0;}

  • getcint getc ( FILE * stream );Get character from streamReturns 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.

  • putcint putc ( int character, FILE * stream );Write character to streamWrites 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 ValueIf 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.

  • fgetschar * fgets ( char * str, int num, FILE * stream );Get string from streamReads 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 ValueOn 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

    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;}

  • fputsint fputs ( const char * str, FILE * stream );Write string to streamWrites 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 ValueOn success, a non-negative value is returned.On error, the function returns EOF.

  • fputs example/* fputs example */#include

    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;}

  • fprintfint fprintf ( FILE * stream, const char * format, ... );Write formatted output to streamWrites 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 Characterd or i Signed decimal integerE Scientific notation (mantise/exponent) using e characterE Scientific notation (mantise/exponent) using E characterf Decimal floating pointg Use the shorter of %e or %f 392.65G Use the shorter of %E or %f 392.65o signed octals String of charactersu Unsigned decimal integerx Unsigned hexadecimal integerX Unsigned hexadecimal integer (capital letters)p Pointer address

  • fscanfint fscanf ( FILE * stream, const char * format, ... );Read formatted data from streamReads 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 ValueOn 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

    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;}