文件I/O-open-close
文件描述符
定义
fileno
- 将文件指针转化为文件描述符
fdopen
- 将文件描述符转化为文件指针
打开或者关闭文件
- <fcntl.h>
open
- <sys/stat.h>:mode_t mode
- <fcntl.h>:int flags
- fail return: -1
flag
mode
- <sys/stat.h>
掩码计算
代码习惯
示例
creat
open和creat等价形式
close
代码习惯
#include <stdio.h>
#include <fcntl.h> // open
#include <stdlib.h> // exit
#include <unistd.h> // close
// #include <sys/types.h>
// #include <sys/stat.h>
int main(void) {
int fd = -1;
char * fileName = "./log.txt";
fd = creat(fileName, 0666);
if (fd == -1) {
perror("fail to creat \n");
exit(EXIT_FAILURE);
} else {
printf("create file %s successfully\n", fileName);
}
close(fd);
return 0;
}
/*
使用IO系统调用
*/
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
int main(int argc, char * argv[])
{
int fdInput, fdOutput, iOpenFlags;
char buf[BUF_SIZE] = {0};
mode_t FilePerms;
ssize_t numRead;
if (argc != 3 || strcmp(argv[1], "--help") == 0)
{
printf("%s old-file new-file\n", argv[0]);
exit(EXIT_FAILURE);
}
/* open input and output file */
fdInput = open(argv[1], O_RDONLY);
if (fdInput == -1)
{
perror("Error open:");
exit(EXIT_FAILURE);
}
iOpenFlags = O_CREAT | O_WRONLY | O_TRUNC;
FilePerms = S_IRUSR | S_IWUSR | S_IRGRP |
S_IROTH | S_IWOTH;
fdOutput = open(argv[2], iOpenFlags, FilePerms);
if (fdOutput == -1)
{
perror("Error open output:");
exit(EXIT_FAILURE);
}
/* Transfer data */
//while ((numRead = read(fdInput, buf, BUF_SIZE)) > 0) // 两种表示方式皆可
while ((numRead = read(fdInput, buf, sizeof(buf))) > 0)
{
printf("%d\n", numRead);
if (write(fdOutput, buf, numRead) != numRead)
{
perror("Error write:");
exit(EXIT_FAILURE);
}
}
if (numRead == -1)
{
perror("Error write:");
exit(EXIT_FAILURE);
}
if (close(fdOutput) == -1)
{
perror("Error write:");
exit(EXIT_FAILURE);
}
if (close(fdInput) == -1)
{
perror("Error write:");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}