Read code:
[email protected] 03]# cat ex03-read-01.c
/* File ex03-open-03.c,
Use of O_creat and O_EXCL * *
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main (void)
{
int FD = -1,i;
ssize_t size =-1;
/* buffer for storing data */
Char buf[10];
Char filename[] = "test.txt";
/* Open file, if file does not exist, then error */
FD = open (filename,o_rdonly);
if ( -1 = = FD) {
/* file already exists */
printf ("Open file%s failure,fd:%d\n", FILENAME,FD);
} else {
/* file does not exist, create and open */
printf ("Open file%s success,fd:%d\n", FILENAME,FD);
}
/* Loop through the data until the end of the file or error */
while (size) {
/* 10 bytes of data per read */
size = Read (fd, buf,10);
if (-1 = = size) {
/* ERROR reading Data */
Close (FD);/* Closes file */
printf ("Read file error occurs\n");
/* return */
return-1;
}else{
/* Read Data successfully */
if (size >0) {
/* Get size bytes of data */
printf ("read%d bytes:", size);
/* Print quotation marks */
printf ("\" ");
/* Print out the data you read */
for (i = 0;i<size;i++) {
printf ("%c", * (Buf+i));
}
/* Print quotation marks and wrap */
printf ("\" \ n ");
}else{
printf ("Reach the end of file\n");
}
}
}
return 0;
}
[Email protected] 03]#./ex03-read-01
Open file Test.txt success,fd:3
Read bytes: "AAAAAAAAAA"
Read bytes: "AAAAAAAAAA"
Read bytes: "AAAAAAAAAA"
Read 5 bytes: "AAAA
"
Reach the end of file
-----Write
[email protected] 03]# cat ex03-write-01.c
/* File ex03-write-01.c,
Use of O_creat and O_EXCL * *
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main (void)
{
int FD = -1,i;
ssize_t size =-1;
int input = 0;
/* buffer for storing data */
Char buf[]= "Quick brown fox jumps over the lazy dog";
Char filename[] = "test.txt";
/* Open file, if file does not exist, then error */
FD = open (filename,o_rdwr| O_TRUNC);
if ( -1 = = FD) {
/* file already exists */
printf ("Open file%s failure,fd:%d\n", FILENAME,FD);
} else {
/* file does not exist, create and open */
printf ("Open file%s success,fd:%d\n", FILENAME,FD);
}
/* Write data to file Test.txt */
Size = Write (FD, Buf,strlen (BUF));
printf ("Write%d bytes to file%s\n", size,filename);
/* Close File */
Close (FD);
return 0;
}
[email protected] 03]# cat Text.txt
Cat:text.txt:No such file or directory
[email protected] 03]# cat Test.txt
Quick brown fox jumps over the lazy dog