open 函数 api学习

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// #include<bits/stdc++.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>

#include<stdio.h>

// #include <iostream>
// using namespace std;

int main(void) {
  
  int fd = 0;
  //打开 已经存在的文件
  fd = open("hello.txt",O_RDWR);
  if (fd == -1) {
    perror("操作错误  open file error");
    exit(1);
  }
  printf("fd:= %d \n",fd);
  //关闭文件
  int res = close(fd);
  printf("res:= %d\n",res);

  //cout << fd <<endl;
  
  
  
  return 0;
}
1
2
3
4
5
6
#编译方法
gcc pid.cpp -o a.out

[root@VM-0-7-centos judgeServer_QD]# ./a.out 
fd:= 3 
res:= 0

打开已经存在的文件,fd 是 3

  1. read

    1. 返回值:

      1. -1 读取文件失败
      2. 0 读取文件成功
      3. $>0$ 读取到的字节数

fprintf 写入文件

linux 下黏贴快捷键: shift + ins [insert]

复制快捷键

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<cstdio>

using namespace std;

//
//
//void get() {
//    char p[] = "hello world";
//}
//


int main(void) {

    char p[] = "hello world";
    FILE *fp = fopen("abc.tt","w");
    if(fp == NULL ) {
        perror("fopen error" );
        return -1;
    }
    //sprintf("result := %d\n" ,1);
    //将输出打印到 aaa.tt 文件里面
    fprintf(fp,"result := %s" ,"dd");
    //关闭文件
    fclose(fp);
    //return
    //printf("hello world %s\n hello world  \n" , p); //    return 0; return 0;






    return 0;

}

大文件拷贝

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include<cstdio>

using namespace std;


int main(void) {

    FILE *read = fopen("./app.txt","r");
    FILE * write = fopen("./txt.out","w");
    char buf[128]={0};
    while(1) {
        int ret =  fread(buf,1,sizeof buf, read);
        if( ret == 0 ) {
            break;
        }
        fwrite(buf,1, ret, write);

    }
    fclose(read);
    fclose(write);

    return 0;

}