Tải bản đầy đủ (.ppt) (45 trang)

Lập trình Linux IO pps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (248.65 KB, 45 trang )

TMA Training Center (www.ttc.edu.com) Slide # 1
Linux I/O Programming
TMA Training Center (TTC)
TMA Training Center (TTC)
TMA Training Center (www.ttc.edu.com) Slide # 2
1. Objective
2. Unix file system
3. Standard I/O Library
- Opening file
- Closing file
- Reading file
- Writing file
- Seeking file
4. Check user's permissions for a file
5. Get file’s status
6. Change permissions of a file
7. Reading The Contents Of Directories
Contents
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 5
Unix INODE Structure
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 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.
a Open for appending (writing at end of file).
a+ Open for reading and appending (writing at end of file).
Standard "C" File Read And Write - Opening a File
(1/3)
TMA Training Center (www.ttc.edu.com) Slide # 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;
f_write = fopen("logfile", "w");
Standard "C" File Read And Write - Opening A File
(2/3)
TMA Training Center (www.ttc.edu.com) Slide # 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)
TMA Training Center (www.ttc.edu.com) Slide # 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
TMA Training Center (www.ttc.edu.com) Slide # 13

The function perror() is prototyped by:
void perror(const char *message);

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()
TMA Training Center (www.ttc.edu.com) Slide # 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:
if (!fclose(f_readwrite)) {
perror("Failed closing file
'/usr/local/lib/db/users':");
exit(1);
}
Standard "C" File Read And Write – Closing a file –
fclose() (1/2)
TMA Training Center (www.ttc.edu.com) Slide # 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)
TMA Training Center (www.ttc.edu.com) Slide # 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()
TMA Training Center (www.ttc.edu.com) Slide # 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()
TMA Training Center (www.ttc.edu.com) Slide # 18
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t
nitems, FILE *stream);
The fread library function is used to read data from a file stream. Data is
read into a data buffer given by ptr from the stream
Read one block of 120 characters from the file stream, into 'buf'. (the third
parameter to fread() is the number of blocks to read):
char buf[120];
if (fread(buf, 120, 1, f_read) != 1) {
perror("fread");
}

Standard "C" File Read And Write - Reading From
An Open File – fread()
TMA Training Center (www.ttc.edu.com) Slide # 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");
fputs(buf, f_readwrite);
Standard "C" File Read And Write - Writiing From
An Open File – fputc()
TMA Training Center (www.ttc.edu.com) Slide # 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)
TMA Training Center (www.ttc.edu.com) Slide # 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'. */
fseek(f_read, 29L, SEEK_START);

/* move the read/write pointer of the file stream 25 characters forward from
its given location. */
fseek(f_read, 25L, SEEK_SET);
Standard "C" File Read And Write - Moving The
Read/Write Location In An Open File – fseek() (2/2)
TMA Training Center (www.ttc.edu.com) Slide # 22
#include <stdio.h>
long ftell(FILE *stream);
The ftell function obtains the current value of the file position indicator for the stream
pointed to by stream
Return value
Upon successful completion, ftell returns the current offset. Otherwise, -1 is returned and
the global variable errno is set to indicate the error.
Example
long old_position = ftell(f_readwrite);
if (old_position < 0) {
perror("ftell");
exit(0);
}
Standard "C" File Read And Write – the current file
offset in a stream – ftell()
TMA Training Center (www.ttc.edu.com) Slide # 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)
TMA Training Center (www.ttc.edu.com) Slide # 24
Check if we have read permission to "/home/my_names“
if (access("/home/my_names", R_OK) == 0)
printf("Read access to file '/home/my_names‘
granted.\n");
else
printf("Read access to file '/home/my_names'
denied.\n");
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
'data.db' is denied.\n");
Accessing Files With System Calls - check user's
permissions for a file (2/4)
TMA Training Center (www.ttc.edu.com) Slide # 25
Check if we may execute the program file "runme".
if (access("runme", X_OK) == 0)
printf("Execute permission to program 'runme'
granted.\n");
else
printf("Execute permission to program 'runme'
denied.\n");
Check if we may write new files to directory "/etc/config".

if (access("/etc/config", W_OK) == 0)
printf("File creation permission to directory
'/etc/sysconfig' granted.\n");
else
printf("File creation permission to directory
'/etc/sysconfig' denied.\n");
Accessing Files With System Calls - check user's
permissions for a file (3/4)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×