Files - PowerPoint PPT Presentation

1 / 16
About This Presentation
Title:

Files

Description:

Files & File Streams. Chapter 21. Files. Everything in Unix is a file. Files. Directories. Ports. Drives. Keyboard. Monitor. All attached devices ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 17
Provided by: alanb9
Category:

less

Transcript and Presenter's Notes

Title: Files


1
Files File Streams
  • Chapter 21

2
Files
  • Everything in Unix is a file
  • Files
  • Directories
  • Ports
  • Drives
  • Keyboard
  • Monitor
  • All attached devices
  • Whether you know it or not, youve been using
    file streams since your hello world program on
    the second day of class. Printf and scanf both
    use file streams to do input and output.

3
File Stream
  • Making calls to read() and write() which are both
    kernel level operations are very costly to
    performance. When a kernel call is made, the
    process releases its control of the CPU and
    waits for the kernel to provide the service
    needed.
  • In addition, reading and writing to secondary
    storage (disk) is thousands of times slower than
    writing to primary storage.
  • File streams were created to help reduce the
    number of times read() and write() calls are
    made, by making use of buffers.

4
Buffering
  • A program that uses file streams reads data
    from, and writes data to its own memory buffers,
    usually one character at a time. Since memory
    access doesnt require a system call, this type
    of buffered I/O can be done very quickly, and
    without blocking. Only when an input buffer is
    empty or an output buffer is full, do the
    programs issue the read() or write() system
    calls.
  • A typical buffer is 1kb or 1024 characters.
  • Types of buffering
  • Block buffering used by disks, and tapes. A
    buffer is flushed only when it is full.
  • Line buffering used for terminals, characters
    are buffered until a newline character is output,
    the buffer is full, or input is requested (which
    makes sure prompts are output before input is
    expected).
  • Unbuffered I/O used when characters must be
    transferred immediately.

5
Opening a File
  • There is no basic file data type in C, but there
    is a FILE structure defined in stdio.h.
  • To open a file, we use the fopen function. fopen
    requires a string with the path and name of the
    file to be opened, and a string to represent the
    mode the file should be opened with.
  • The path to the file can be either be the full
    path or a relative path.
  • The mode can be one of 6 things
  • r read only
  • w writing only. If the file exists, it will
    be overwritten.
  • a writing only. If the file exists, data is
    appended to the end of the file.
  • r reading writing. Data writing starts at
    the beginning of the file, and the file contents
    may be overwritten.
  • w reading writing. Existing file contents
    are erased before the first read or write
    operation.
  • a reading writing. Like r except
    position is initially the end of the file.

6
Opening a File
  • The fopen function will return a pointer to a
    FILE structure, or NULL if the file is unable to
    be opened. Your programs should check if NULL
    was returned from fopen and deal with that
    condition since C wont check for an error or do
    error handling automatically for you.
  • ExamplesFILE out
  • out fopen(/users/student/student_a/out.txt,w
    )
  • out fopen(./out.txt,a)

7
Closing a File
  • The fclose function flushes output buffers, then
    closes the file.
  • fclose(out)

8
Getting Putting Characters
  • There are two options for getting characters from
    a file stream. getc and fgetc both of which take
    the FILE as their argument and return the next
    character read from the file or EOF if end of
    file is reached. getc is implemented as a
    preprocessor macro so it is much faster than
    fgetc, which is implemented as a function.
  • There are two options for putting characters out
    to a file stream as well. They are putc and
    fputc and each takes the character to be written
    and the FILE to write to. They will return the
    character written or EOF to indicate an error.
    Again as with getc, putc is implemented as a
    macro and will be much faster than fputc which is
    implemented as a function.

9
Reading Writing Strings
  • Fgets get a string from a file stream
  • Char fgets(char string, int maxlen, File
    stream)
  • Gets a string from the specified file stream and
    stores it in the address pointed at in the first
    argument. A string is defined as ending with a
    new line character or having up to maxlen
    characters.
  • Fputs writes a string to a file stream
  • Int fputs(char string, FILE stream)
  • Writes the string specified as the first argument
    to the stream specified in the second argument.
    Returns 0 on success or EOF on error.

10
Formatted Input Output
  • Fscanf reads a formatted string. Identical to
    scanf except it reads from the specified file
    stream instead of from standard input.
  • Int fscanf(FILE stream, char format,)
  • Returns the number of items converted.
  • Fprintf writes formatted numeric data and text
    to a stream. Identical to printf except it
    prints to a stream instead of standard output.
  • Int fprintf(FILE stream, char format, )
  • Returns the number of characters printed.

11
Checking for EOF
  • There is a macro called feof which is meant
    specifically to check for the EOF condition. The
    only drawback is that it is only set after a read
    operation fails due to an end of file condition.
  • feof(FILE )
  • Will return a non-zero number if an EOF condition
    has been met.
  • Because feof doesnt work until after a read
    operation, youve already got the EOF flag back
    from your read operation by the time you can call
    feof and get it to report back an EOF. Because
    youll have to check your data returned from the
    read operation for EOF anyway, theres no use
    using feof. This is a better solution
  • While( (chgetc(input)) ! EOF )

12
Temporary Files
  • Often times youll need to use a file to
    temporarily store some data. If you hard code a
    name into your program, you can never be sure
    that it will never overwrite another file. C
    provides some functions for creating temporary
    files with names that are guaranteed not to
    interfere with any currently existing files.
  • tmpnam(char name) generates a unique file name
    in the system temp directory (/tmp) and stores
    the name in the string that was passed in as an
    argument.
  • tempnam(char dir, char prefix) also generates a
    unique file name but allows you to specify the
    directory you want the file in with the first
    argument. The second argument is a prefix for
    the file, so if you pass in a prefix of temp,
    the filename that tempnam returns will begin with
    temp followed by a sequence of random letters
    and/or digits.
  • Each of the above functions returns a string with
    the path to a unique temporary file name. You
    can then create the file with fopen.
  • A word of warning If you call either of the
    above functions more than once without using the
    name(s) previously generated, they could return a
    duplicate name.

13
Clearing Buffers
  • Sometimes its necessary to make sure that your
    data is moved from the buffer to the file or
    screen. You can do this with the fflush
    function. With this function, you dont lose any
    data, it just forces the data to be written.
  • fflush(stdout)
  • The other option for clearing a buffer is fpurge.
    This function is a destructive one, and will
    delete whatevers in the buffer rather than
    writing it out. This comes in handy when using
    scanf. Some of you have noticed that its
    necessary to put a blank white space at the
    beginning of your format string in a scanf call
    in order to keep your program from skipping the
    part where the user is allowed to enter their
    data. This is because there is a left over white
    space stuck in the stdin stream buffer. A call
    to fpurge(stdin) just prior to your scanf call
    will clean the buffer, removing the white space
    and the removing the need to have a leading white
    space in your scanf format string.
  • Linux does not use fpurge, it uses __fpurge
    instead which is provided by stdio_ext.h

14
Error Handling
  • Thankfully, the C libraries provide plenty of
    error feedback. Most of that feedback is
    provided by a global integer variable called
    errno. If an I/O error occurs, the resulting
    error code will generally be put in errno. You
    can then use errno to output error messages or
    debug your program.
  • There are a couple of functions that will help
    make your life easier with error handling
  • ferror(FILE stream) returns a non-zero integer
    if the specified stream has encountered an error.
  • perror(char error_string_prefix) Prints the
    error string prefix provided as an argument to
    standard output followed by a colon and textual
    description of the error that occurred.
  • strerror(int err_code) - returns a string
    describing the error that corresponds with the
    error code passed in. Can be used as
    follows char error error strerror(errno)

15
Whole File Operations
  • Deleting a file
  • remove(char path)
  • unlink(char path)Both remove and unlink are
    identical in functionality, just the name differs
  • Move or rename a file
  • rename(char from, char to)
  • Making a directory
  • mkdir(char path, mode)
  • The mode argument in the mkdir call is the
    permissions you want set on the file when it is
    created. The mode number is the same as the
    permissions you would use in the chmod command.
    Ie 755, 700, 644

16
Miscellaneous Stream Functions
  • The following functions are helpful for working
    with files, but we likely wont need them in this
    course. I mention them here for completeness.
    If you need to use them or want more information,
    consult the man pages.
  • fseek moves the files positional pointer to
    the specified character position within the file.
  • ftell returns the current location of the
    files positional pointer within the file.
  • rewind allows you to move the positional
    pointer back to the beginning of the file.
Write a Comment
User Comments (0)
About PowerShow.com