10. System file I/O

All these tasks are performed in parallel by students and trainer in demoscreen mode.

Filesystem objects variety:

OS file I/O

<!> Make a directory named 10_fileio and cd to it. All current programs must reside here. If you using your computer for lab, scp source files here

  1. See read and write. Note stdin, stdout and stderr descriptors standard numbers.

  2. (!) Write a program, that reads a char from stdin, increments it by 1, and writes it to stdout. Note &c notation.

    • Do not forget to #include all the headers mentioned in the manual page

    • Press ^D to close stdin from terminal (this character, like ^C, is not passed to program, but interpreted by OS instead, see stty -a.

  3. See open.

    • Flags are used to indicate how file is opened. Flags are bits so use bitwise OR|») to combine them.

      • O_RDONLY is used for opening for reading

      • O_WRONLY|O_CREAT|O_TRUNC is used for opening for writing

    • Mode parameter is required when creating the file. It provides file access rights, which will be described later. Leave it to 0644 (octal number) for now.

  4. (!) write next program, that reads 100 words (integetrs) from /dev/stdin and writes them to file named outfile

    • Do not forget to close files
    • Remove outfile and try to open("outfile", O_WRONLY|O_CREAT|O_TRUNC) without mode.

      • Note successful compiling, with no error message
      • ls -l outfile produce junk characters in the second column

      • This is because open() uses third parameter from stack, taking junk value

      • No runtime-error occured because this part of stack is free fo use!
      • Check the result by hexdump -C outfile

    • (!) Modify the program to accept command line arguments (using argc/argv):

      1. Number of words (use sscanf to scanf from argv[1])

      2. Name of output file
    • (!) (optional, if there's time for it) Try to:

      • remove O_CREAT flag and get an error message from open() while creating new file

      • remove O_TRUNC flag and notice output file doesn't shrink, but the program just overwrites the beginning of file

  5. See lseek.

  6. (!) Write last program that takes two parameters — input file name and output file name. The program reads words from input file, sorts them and outputs the result to output file.

    • Use malloc() to allocate integer array

    • Any simple sorting algorithm (e. g. bubble-sort or swap-sort) will do

    • Define input file size by lseek()-ing to it's end

    • Do not forget to lseek back to file start (or no data will be read after file end)

    • Check the result with od -l input_file and od -l output_file

H/W

All three programs must reside in 10_fileio subdirectory of your home directory on sugon server. Use scp if you've done the task outside the server.

HSE/ProgrammingOS/Lab_10_FileIO (последним исправлял пользователь FrBrGeorge 2020-02-28 10:32:29)