Skip to content

Commit

Permalink
Merge branch 'master' of github.com:yangbodong22011/linux-book
Browse files Browse the repository at this point in the history
  • Loading branch information
yangbodong committed Oct 8, 2015
2 parents a72d887 + a52b0de commit 00dae1c
Showing 1 changed file with 32 additions and 24 deletions.
56 changes: 32 additions & 24 deletions system-call/chapter-2/OpenReadWriteAndCloseFile.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,52 @@
在C语言中,我们使用fopen、fscanf、fprintf和fclose等函数来使文件打开、读写和关闭。但在linux系统编程中,我们使用open、read、write和close系统调用对文件进行操作。我们先上代码:

```c
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>

int main(int argc , char * argv[]) {
int fd ;
if((fd = open("./1.text" , O_WRONLY | O_CREAT | O_TRUNC , 0777)) < 0) { //打开文件,得到文件描述符
fprintf(stderr , "open file error ");
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

int main(int argc , char * argv[])
{
int fd;

// 打开文件,得到文件描述符
if ((fd = open("./1.text", O_WRONLY|O_CREAT|O_TRUNC, 0777)) < 0) {
perror("open file error: ");
exit(-1);
}

char writedata[100];
char recvdata[100];

strcpy( writedata , "Hello world!\n"); //准备要写入文件的数据
// 准备要写入文件的数据
strcpy(writedata, "Hello world!\n");

/*
在这里我们先向目标文件中写入数据
接下来再从目标文件中读取数据
*/
// 在这里我们先向目标文件中写入数据
// 接下来再从目标文件中读取数据

if(0 > write(fd , writedata , strlen(writedata)+1)) { //给文件写入数据
printf("write data in file error!\n");
// 给文件写入数据
if (0 > write(fd, writedata, strlen(writedata)+1)) {
perror("write data in file error: ");
exit(-1);
}
close(fd); //关闭文件描述符
// 关闭文件描述符
close(fd);

if((fd = open("./1.text" , O_RDONLY , 0777)) < 0) { // 打开文件,得到文件描述符
printf("open file error!\n");
// 打开文件,得到文件描述符
if ((fd = open("./1.text", O_RDONLY, 0777)) < 0) {
perror("open file error: ");
exit(-1);
}
if(0 > read(fd , &recvdata , 100)) { //从文件中读取数据保存到recvdata里
printf("read file error!\n");

// 从文件中读取数据保存到recvdata里
if (0 > read(fd, &recvdata, 100)) {
perror("read file error: ");
exit(-1);
}
printf("%s" , recvdata);

printf("%s", recvdata);
close(fd); //关闭文件描述符

return EXIT_SUCCESS;
Expand All @@ -63,4 +71,4 @@ marking...
##系统调用——close
marking...
marking...

0 comments on commit 00dae1c

Please sign in to comment.