1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình Linux IO pps

45 526 4
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 167 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

include FILE *fopenconst char *path, const char *mode; The argument mode points to a string beginning with one of the following sequences r Open text file for reading.. */ perror"Fail

Trang 1

Linux I/O Programming

TMA Training Center (TTC)

Trang 2

1 Objective

2 Unix file system

3 Standard I/O Library

4 Check user's permissions for a file

5 Get file’s status

6 Change permissions of a file

Contents

Trang 3

 The following tutorial describes various common

methods for reading and writing files and directories

on a Unix system

 Part of the information is common C knowledge, and is repeated here for completeness

Objectives

Trang 4

 Files are stored in the filesystem in two pieces:

 (1) a chunk of data somewhere in the filesystem;

 (2) a data structure which contains: location, size,

creation/modification/access times, ownership, access attributes of

and links to the file This data structure is called an "inode.“ The

only thing about the file not included in the inode is the name of the file

Unix File System

Trang 5

Unix INODE Structure

Trang 6

 One of the unique things about Unix as an operating system

is that regards everything as a file

 Files can be divided into four categories

 Ordinary or plain files

 Directories

 Special or device files

 Links

Everything is a File

Trang 7

 / - Special file system that incorporates the files under several directories including /dev, /sbin, /tmp etc

 /usr - Stores application programs

 /var - Stores log files, mails and other data

 /tmp - Stores temporary files

A few of the file system

Trang 8

 The FILE structure is the basic data type used when handling files with the standard C library

 When we open a file, we get a pointer to such a structure, that we later use with all other operations on the file, until we close it

Standard "C" File Read And Write - FILE

Structure

Trang 9

In order to work with a file, we must open it first, using the fopen() function

include <stdio.h>

FILE *fopen(const char *path, const char *mode);

The argument mode points to a string beginning with one of the following sequences

r Open text file for reading

r+ Open for reading and writing

w Truncate file to zero length or create text file for writing

w+ Open for reading and writing

Standard "C" File Read And Write - Opening a File (1/3)

Trang 10

Open the file /home/choo/data.txt for reading

FILE* f_read;

f_read = fopen("/home/choo/data.txt", "r");

if (!f_read) { /* open operation failed */

perror("Failed opening file '/home/choo/data.txt' for reading:");

exit(1);

}

Open the file logfile in the current directory for writing.

/* if the file does not exist, it is being created

if the file already exists, its contents is erased */

FILE* f_write;

Standard "C" File Read And Write - Opening A File (2/3)

Trang 11

Open the file /usr/local/lib/db/users for both reading and writing

/* Any data written to the file is written at the beginning of the file, over-writing the existing data */

FILE* f_readwrite;

f_readwrite = fopen("/usr/local/lib/db/users",

"r+");

Open the file /var/adm/messages for appending.

/* Any data written to the file is appended to its end */

FILE* f_append;

f_append = fopen("/var/adm/messages", "a");

Standard "C" File Read And Write - Opening A File (3/3)

Trang 12

errno is a special system variable that is set if a system call cannot

perform its set task It is defined in #include <errno.h>

To use errno in a C program it must be declared via:

extern int errno;

It can be manually reset within a C program (although this is uncommon practice) otherwise it simply retains its last value returned by a system call or library function

Standard "C" File Read And Write - errno

Trang 13

 The function perror() is prototyped by:

 perror() produces a message (on standard error output), describing the last error encountered, returned to errno (see below) during a call to a system or library function

 The argument string message is printed first, then a colon and a blank, then the message and a newline If message is a NULL pointer or

points to a null string, the colon is not printed

Standard "C" File Read And Write -

perror()

Trang 14

 Once we are done working with the file, we need to close it This has two effects:

- Flushing any un-saved changes to disk (actually, to the operating

system's disk cache)

- Freeing the file descriptor (will be explained in the system calls section below) and any other resources associated with the open file

 Closing the file is done with the fclose() function, as follows:

Trang 15

 fclose() returns 0 on success, or EOF (usually '-1') on failure

It will then set "errno" to zero

 One may wonder how could closing a file fail - this may

happen if any buffered writes were not saved to disk, and are being saved during the close operation

 Whether the function succeeded or not, the FILE structure may not be used any more by the program.

Standard "C" File Read And Write – Closing a file – fclose() (2/2)

Trang 16

Once we have a pointer for an open file's structure, we may read from it using any of several functions

#include <stdio.h>

int fgetc(FILE *stream);

The fgetc function returns the next byte, as a character, from a file stream When it reaches the end of the file or there is an error, it returns EOF You must use ferror or feof to distinguish the two cases

int c;

c = fgetc(f_read);

Standard "C" File Read And Write - Reading

From An Open File – fgetc()

Trang 17

#include <stdio.h>

char *fgets(char *s, int n, FILE *stream);

The fgets function reads a string from an input file stream It writes

characters to the string pointed to by s until a newline is encountered,

n-1 characters have been transferred, or the end of file is reached,

whichever occurs first

fgets(buf, 201, stdin);

Standard "C" File Read And Write - Reading

From An Open File – fgets()

Trang 18

Standard "C" File Read And Write - Reading

From An Open File – fread()

Trang 19

#include <stdio.h>

int fputc(int c, FILE *stream);

Just like the read operations, we have write operations as well They are performed at the current location of the read/write pointer kept in the FILE structure

int 'a';

char buf[201];

c = fputc(c, f_readwrite);

strcpy(buf, "hello world");

Standard "C" File Read And Write - Writiing From An Open File – fputc()

Trang 20

#include <stdio.h>

int fseek(FILE *stream, long int offset, int whence);

The fseek() function allows us to move the read/write pointer of a file

stream to a desired location, stated as the number of bytes from the beginning of the file (or from the end of file, or from the current position

of the read/write pointer)

Standard "C" File Read And Write - Moving The Read/Write Location In An Open File – fseek() (1/2)

Trang 21

/* move the read/write pointer of the file stream to position '30' in the file Note that the first position in the file is '0', not '1' */

Trang 22

#include <stdio.h>

long ftell(FILE *stream);

The ftell function obtains the current value of the file position indicator for the stream

Trang 23

 Since Unix supports access permissions for files, we would sometimes need to check these permissions, and perhaps also manipulate them

 Two system calls are used in this context, access() and chmod()

 The access() system call is for checking access permissions to a file

#include <unistd.h>

int access(const char *pathname, int

mode);

Accessing Files With System Calls - check

user's permissions for a file (1/4)

Trang 24

Check if we have read permission to "/home/my_names“

Check if we have both read and write permission to "data.db".

if (access("data.db", R_OK | W_OK) == 0)

printf("Read/Write access to file 'data.db' granted.\n");

else

printf("Either read or write access to file

Accessing Files With System Calls - check

user's permissions for a file (2/4)

Trang 25

Check if we may execute the program file "runme"

Accessing Files With System Calls - check

user's permissions for a file (3/4)

Trang 26

Check if we may read the contents of directory "/etc/config".

if (access("/etc/config", R_OK) == 0)

printf("File listing read permission to

directory '/etc/sysconfig' granted.\n");

else

printf("File listing read permission to

directory '/etc/sysconfig' denied.\n");

Check if the file "hello.world" in the current directory exists

if (access("hello world", F_OK) == 0)

printf("file 'hello world' exists.\n");

else

printf("file 'hello world' does not exist.\n");

Accessing Files With System Calls - check

user's permissions for a file (4/4)

Trang 27

 Note that we cannot use access() to check why we got permissions (i.e if it was due to the given mode granted to us as the owner of the file, or due to its group permissions or its word permissions)

 For more fine-grained permission tests, see the stat() system call mentioned below

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

int stat(const char *file_name, struct stat *buf);

Accessing Files With System Calls - Get file’s status (1/4)

Trang 28

struct stat {

dev_t st_dev; /* device */

ino_t st_ino; /* inode */

mode_t st_mode; /* protection */

nlink_t st_nlink; /* number of hard links */

uid_t st_uid; /* user ID of owner */

gid_t st_gid; /* group ID of owner */

dev_t st_rdev; /* device type (if inode device) */ off_t st_size; /* total size, in bytes */

blksize_t st_blksize;/* blocksize for filesystem I/O */ blkcnt_t st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last access */

time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last change */

Accessing Files With System Calls - Get file’s status (2/4)

Trang 29

Structure passed to the stat() system call, to get its results.

struct stat file_status;

Check the status information of file "foo.txt", and print its type on screen

Trang 31

#include <sys/types.h>

#include <sys/stat.h>

int chmod(const char *path, mode_t mode);

The mode of the file given by path or referenced by fildes is changed

Modes are specified by or'ing the following:

S_ISUID 04000 set user ID on execution S_ISGID 02000 set group ID on execution S_ISVTX 01000 sticky bit

S_IRUSR (S_IREAD) 00400 read by owner

S_IWUSR (S_IWRITE) 00200 write by owner

S_IXUSR (S_IEXEC) 00100 execute/search by owner S_IRGRP 00040 read by group

Accessing Files With System Calls - Change

permissions of a file – chmod() (1/2)

Trang 32

S_IWOTH 00002 write by others

S_IXOTH 00001 execute/search by others

Give the owner read and write permission to the file "blabla", and deny access to any other user

if (chmod("blabla", S_IRUSR | S_IWUSR) == -1) { perror("chmod");

} Accessing Files With System Calls - Change

permissions of a file – chmod() (2/2)

Trang 33

 The rename() system call may be used to change the name (and possibly the

directory) of an existing file

#include <sys/types.h>

#include <sys/stat.h>

int rename(const char *oldname, const char

*newname);

 If the new name points to a an already existing file, that file is deleted first We are

allowed to name either a file or a directory

/* rename the file 'logme' to 'logme.1' */

Accessing Files With System Calls - Renaming A File – rename()

Trang 34

Remove a file is done using the unlink() system call

/* remove the file "/tmp/data" */

Trang 35

We have encountered symbolic links earlier lets see how to create them, with the symlink() system call:

Create a symbolic link named "link" in the current directory,

that points to the file "/usr/local/data/datafile"

Trang 36

In order to read the contents of a directory, we first open it, using the opendir() function

We supply the path to the directory, and get a pointer to a DIR structure in return (or NULL on failure) Here is how:

#include <sys/types.h>

#include <dirent.h>

DIR *opendir(const char *name);

/* open the directory "/home/users" for reading */ DIR* dir = opendir("/home/users");

Trang 37

#include <sys/types.h>

#include <dirent.h>

int closedir(DIR *dirp);

When we are done reading from a directory, we can close it using the closedir() function:

if (closedir(dir) == -1) {

perror("closedir");

exit(1);

}

closedir() will return '0' on success, or '-1' if it failed Unless we have done something really

Reading The Contents Of Directories - Closing

A Directory – closedir()

Trang 38

#include <sys/types.h>

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

After we opened the directory, we can start scanning it, entry by entry, using the readdir() function The first call returns the first entry of the directory Each successive call

returns the next entry in the directory When all entries have been read, NULL is

returned Here is how it is used:

struct dirent* entry;

/* read the directory's contents, print out the name of each entry */

printf("Directory contents:\n");

while ( (entry = readdir(dir)) != NULL) {

Reading The Contents Of Directories - readdir()

Trang 39

 rewinddir - reset position of directory stream to the beginning of a directory

#include <sys/types.h>

#include <dirent.h>

void rewinddir(DIR *dirp);

 After we are done reading the contents of a directory, we can rewind it for a second pass, using the rewinddir() function:

rewinddir(dir);

Reading The Contents Of Directories Rewinding

A Directory – rewinddir()

Trang 40

#include <unistd.h>

char *getcwd(char *buf, size_t size);

Sometimes we wish to find out the current working directory of a process The getcwd() function is used for that Other times we wish to change the working directory of our process This will allow using short paths when accessing several files in the same directory The chdir() system call is used for this Here is an example:

Trang 41

1 Write a program to copy one named file into another named file The two file names are given as the first two arguments to the program Copy the file a block (512 bytes) at a time

Check: that the program has two arguments or print "Program need two arguments" that the first name file is readable or print "Cannot open file for reading" that the second file is writable or print "Cannot open file for writing"

2 Write a program last that prints the last n lines of a text file, by n and the file name

should be specified form command line input By default n should be 5, but your

program should allow an optional argument so that

last -n file.txt

Exercises (1/2)

Trang 42

3 Write a program to compare two files and print out the lines where they differ Hint: look up appropriate string and file handling library routines This should not be a very long program

Exercises (2/2)

Trang 43

 We have learned how to use the standard C library I/

O functions for managing file system in Linux

Summary

Trang 44

Linux Programming Unleashed

Author: Kurt Wall, Mark Watson, and Mark Whitis

SAMS http://portal.aauj.edu/portal_resources/downloads/operating_system/ linux_programming_unleash.pdf

Advance Linux Programming

Author: Mark Mitchell, Jeffrey Oldham, and Alex Samuel

Copyright © 2001 by New Riders

FIRST EDITION: June, 2001

http://www.advancedlinuxprogramming.com/downloads.html

Inode structure

http://en.wikipedia.org/wiki/Inode

References

Ngày đăng: 29/07/2014, 14:20

TỪ KHÓA LIÊN QUAN