Hello, We’ll go through some advanced operations about the files.
We will learn in the next example these functions:
- fopen – open a file
- fgets – read a specific amount of a file
- fgetc – read a character of a file
- fexists – check if a file exists
- freopen – re-open a file in a file handler
- fseek ( file_handle, offset, whence ) – set the position of the stream, whence: ( 0=beginning of the file, 1=current position, 2=end of the file)
- rewind – set back the position to the beginning of the file
- fgetpos & fsetpos – get handle of the current position and set new position for the file
- fputc – write a single character
- fputs – write a text
- fwrite – write a text
- fread – read a specific amount of a file
- ftell – know the current position
- fclose – close the file handler
/* r - read w - write new or overwrite a - appends and creates new if doesn't exists r+ - read & write (update file) w+ - read & write a+ - read & append */ file = fopen('somewhere.txt', 'r') see file see fgets(file, 100) #the same result as above. see fgetc(file) #returns a character or EOF see fexists('some_other_file.txt') #returns 0 (false), 1 (true) file = freopen('some_other_file.txt', 'r+') fseek(file, 0 , 2) #go to the end of the text file see ftell(file) fputc(file, 'a') #append a character fputs(file, 'amr') #append a text rewind(file) #set back the position to the beginning of the file. fwrite(file, 'consider this a something just for the example, ty.') #writes to the file fread(file, 100) #returns 100 characters from the file x = fgetpos(file) #returns position handle fsetpos(file, 5) #set new position of the file fclose(file) #close the file handler.
There’re two functions for this.
x = tempfile() #returns a file handle for a temp file. x = tempname() #returns a temp file name that doesn't exists
clearerr(file) #clear the EOF error and the error indicators of a stream.
see feof(file) #returns 1 if it's the end of the file, 0 if it's not.
see ferror(file) #returns 1 if there's error indicator, 0 if not.
perror('error happened') #print error message to the stderr.
We can flushes the output buffer of a stream using the Fflush() function.
We can push a character to the stream using this function so
the character will be available for the next read.
Well, at this point we’re done of the files chapter.
see you in the next chapter.