Docsity

Working with the File - Linux System Programming - Lecture Notes, Study notes of Linux skills

Partial preview of the text

Download Working with the File - Linux System Programming - Lecture Notes and more Study notes Linux skills in PDF only on Docsity!

Working With Files

Introduction

Files

  1. In UNIX system or UNIX-like system, all input and output are done by reading or writing files, because all peripheral de- vices, even keyboard and screen are files in the file system.
  2. This means that a single homogeneous interface handles all communication be- tween a program and peripheral devices.In general, programs can use disk files, se- rial ports, printers and other devices in exactly the same way as they would.
  3. UNIX provides a simple and consistent in- terface to operating system services and to devices.

Directories 1

#define DIRSIZ 14 /* end of the conditional processor*/ #endif

/* the structure of directory / struct directory { / type of ino_t, inode number*/ ino_t d_ino;

/* directory name, an array of size DIRSIZ */ char d_name[DIRSIZ]; }

UNIX system User space: user program library

Kernel space: System Calls kernel Devices Driver

Hardware

This is a hierarchy view of Unix system, where various file functions exist in uer space and kernel space in the different levels, and com- plete different jobs.

  1. System calls The Unix system provides its service through a set of system calls, which are in ef- fect functions within the operating sys- tem that may be called by user programs. It is sometimes important to employ sys- tem calls to achieve maximum efficiency, or to access some facilities that are not in library. And parts of standard library can be im- plemented with system calls.
  2. Device drivers The Kernel consists of a number of de- vice drivers, which are a collection of lower- level interfaces for controlling system hard- ware.

If you read and write a file, the system will check:

  1. Does this file exit?
  2. Do you have permission to access it?

If all is well, it will return to the program a small non-negative integer, and this is file descriptor.

convention

when the shell run a program, three files are open, with file descriptors 0, 1, and 2, called the standard input, the standard output, and standard error.If a program reads 0, writes 1 and 2, it can do input and output without worrying about open- ing files.

How it works?

Whenever input or output is to be done on the file, the file descriptor is used in- stead of the name to identify the file.

For example:

ls -l >lsoutput.txt

In this case, the shell interpret the com- mand of ls -l and reads into file descrip- tors 0 and writes to the named file(lsoutput.txt). And file descriptor 2 remains attached to the screen, so error message can go there.

is used for output: putchar(c) puts the character c on the standard output, which is by default the screen. putchar returns the character written, or EOF if an error occurs.

Each source file refers to an input/output library function must contain the line:

#include <stdio.h>

โ€œ < ... >โ€ฒโ€ฒ^ tells compiler to search the header file in a standard place, e.g /usr/include.

One example: A program converts its input to lower case.

#include <stdio.h> #include <ctype.h>

main()

int c;

while((c = getchar()) !=EOF) putchar(tolower(c)); return 0; }

Here, function tolower() is defined in < ctype.h >; it converts an upper case letter to lower case, and returns other characters untouched.

Type in this program and compile it. Execute this program to see how the system catch your input from keyboard and convert your input into lower case, and show the result on the screen.

File Access

The standard input/output concerns the sys- tem devices, which are automatically defined by local operating system.

file is being read or written, and whether errors or end of file have occurred.

fp = fopen(name, mode)

The first argument is the name of the file, the second argument is the mode, such as โ€œrโ€, โ€œwโ€, โ€œaโ€. Reading an non-exist file is an error!!! Writing or appending an non-exist file may create a new file. If any errors occurs, the fopen will return NULL.

  1. How to read and write a file?

The function

int getc(FILE *fp)

returns the next character from the stream referred to by fp; and returns EOF for end of file or error.

The function

int putc(int c, FILE *fp)

writes the character c to the file fp and returns the character written, or EOF if an error occurs.

The FILE is a structure declared in < stdio.h >. Its usage is as followed:

FILE *fp; FILE *fopen(char *name, char *mode)

This says that fp a pointer to a FILE, and fopen returns a pointer to a FILE.

  1. Error handling -stderr and Exit

Sometimes trouble comes out that a file is not accessible for some reason. We need to know the error occurs where, and easier for debugging.

FILE *fp; void filecopy(FILE *, FILE *); char *prog = argv[0];

if(argc==1) filecopy(stdin, stdout); else while(--argc > 0) if((fp = fopen(*++argv, โ€˜โ€˜rโ€™โ€™))==NULL){ fprintf(stderr, โ€˜โ€˜%s: canโ€™t open %s\n", prog, *argv); exit(1); }else{ filecopy(fp, stdout); fclose(fp); } if(ferror(stdout)){ fprintf(stderr,โ€™โ€™%s: error writing stdout\nโ€™โ€™,p exit(2); } exit(0); }

void filecopy(FILE *ifp, FILE *ofp)

int c;

while((c=getc(ifp)) !=EOF) putc(c, ofp); }

The program signals errors two ways:

First, the diagnostic produced by fprintf goes onto stderr, so it finds way to the screen instead of disappearing down a pipeline or into an output file.

Second, the program uses the standard library function exit, with argument of non-zero integer to indicate an error.

The function int f error(F ILE โˆ— f p) re- turns non-zero if an error occurred on the output stream fp. This situation is very rare, but it may happen, for example, the disk fills up, no enough space for writing on.

Normally, fgets returns line; on end of the file or error it returns NULL.

char *fputs(char *line, FILE *fp)

fputs writes a string(which need not contain a newline) to a file, it returns EOF if an error occurs, and zero otherwise.

Formatted input and output

  • Formatted output

int printf(char *format, arg_1, arg_2)

printf converts, formats, and prints its arguments on the standard output under control of the format. It returns the num- ber of characters printed. The commonly used format are:

  • Formatted input

int scanf(char *format, ...)

The function scanf is the input analog of printf, providing many of the same conversion facilities in the opposite direc- tion.scanfreads characters from the stan- dard input, interprets then according to the specification in format, and store the results through the remaining arguments. But be aware, the arguments to scanf must be pointers. The most common error is writing

scanf(โ€˜โ€˜%dโ€™โ€™, n);

instead of writing

scanf(โ€˜โ€˜%dโ€™โ€™, &n);

The common used format are :

For example: /* A small calculator */

#include <stdio.h>