1, write the number
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h >
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFER _size 1024
#define FILE_PATH "./file.txt"
*
* * Program Entry
*
/int main (int argc,char **argv)
{ C13/>int test_fd =-1;
int ret = 1;
int buffer =;
int num = 0;
/* Open or create the source file and truncate the file length to 0*/
if (Test_fd=open (File_path, o_rdwr| O_creat| O_trunc) ==-1)
{
printf ("Open%s error\n", file_path);
Exit (1);
}
/* Write a number/
ret = write (test_fd, &buffer, sizeof (int));
if (Ret < 0)
{
printf ("Write error\n");
Exit (1);
}
printf ("Write%d byte (s) data\n", ret);
/* Move the file pointer to the beginning to read the number written in the file * *
Lseek (test_fd, 0L, seek_set);
ret= Read (test_fd, &num, sizeof (int));
if (ret==-1)
{
printf ("Read error\n");
Exit (1);
}
printf ("Read%d byte (s) data,the number is%d\n", ret, num);
Close (TEST_FD);
Exit (0);
}
2, writing to the struct body
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <sys/
stat.h> #include <fcntl.h> #include <unistd.h> #define FILE_PATH "./file.txt" typedef struct FILE_RECORD
{int index;
int file_size;
time_t TIMEP;
}file_record;
int main () {int ret = 0;
int FD =-1;
time_t TIMEP = 0;
File_record File_record;
struct stat buf;
memset (&file_record, 0, sizeof (File_record));
memset (&buf, 0, sizeof (struct stat));
Time (&TIMEP);
Stat (File_path, &buf); /* Open or create the source file and truncate the file length to 0*/if (Fd=open (File_path, o_rdwr| O_creat|
O_trunc) ==-1) {printf ("Open%s error\n", File_path);
Exit (1);
} file_record.index = FD;
File_record.file_size = buf.st_size;
FILE_RECORD.TIMEP = TIMEP;
/* Write to a struct/ret = write (fd, &file_record, sizeof (File_record));
if (Ret < 0) {printf ("Write error\n");
Exit (1);
printf ("Write%d byte (s) data\n", ret); memset (&file_record, 0,sizeof (File_record));
/* Move the file pointer to the beginning to read the structure written in the file * * Lseek (FD, 0L, Seek_set);
ret= Read (FD, &file_record, sizeof (File_record));
if (ret==-1) {printf ("read error\n");
Exit (1);
printf ("Read%d byte (s) data,the time is%s\n", ret, CTime (& (FILE_RECORD.TIMEP));
Close (FD);
Exit (0); }