一、打开与创建
1.1.打开文件
在 Ubuntu 的终端中,通过编写 C 语言程序也可以实现打开文件,并对其进行编写,首先创建一个编写代码的环境,并在里面调用打开文件的函数int open(const char *pathname, int flags);该函数是返回一个整数是它的文件描述符,对特定的文件写入、读取就是依靠文件描述符来确定文件。第一个参数是要打开的文件名或路径,第二个参数是打开标志:
| 标志 | 含义 | 说明 |
|---|---|---|
| O_RDONLY | 只读 | 只能读取文件 |
| O_WRONLY | 只写 | 只能写入文件 |
| O_RDWR | 读写 | 可以读取和写入 |
| O_CREAT | 创建 | 文件不存在时创建 |
| O_APPEND | 追加 | 写入时追加到文件末尾 |
| O_TRUNC | 清空 | 打开时清空文件内容 |
| O_EXCL | 排他 | 与O_CREAT一起使用,文件存在则失败 |
下面是打开文件的程序:
//前三个头文件是官方提出是必要的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("new1",O_RDWR); //打开 new1 文件并且可读可写
if(fd > 0)
{
printf("file open success\n");
}
return 0;
}
1.2.创建文件
如果打开的是一个不存在的文件,可以使用这个打开函数: int open(const char *pathname, int flags, mode_t mode);前两个参数和上小节一样,第三个参数是文件权限:
| 权限值 | 含义 (八进制) | 说明 |
|---|---|---|
| 0644 | -rw-r–r– | 用户可读写,其他人只读 |
| 0755 | -rwxr-xr-x | 用户可读写入执行,其他人只读执行 |
| 0600 | -rw------- | 仅用户可读写 |
| 0666 | -rw-rw-rw- | 所有人都可读写 |
使用该函数创建一个文件都要匹配文件权限:
int main()
{
int a;
a = open("new2",O_RDWR);
if(a > 0)
{
printf("file open success\n");
}
else
{
open("new2",O_RDWR|O_CREAT,0600); //第二个参数的打开标志可以使用或操作
//这个函数意思是创建new2文件可读可写,文件权限也是可读可写
printf("file has been created!\n");
}
return 0;
}
二、写入与读取
2.1.对文件写入
使用ssize_t write(int fd, const void *buf, size_t count);函数对特定文件进行写入操作,第一个参数是文件标识符,第二个参数是一个存放写入内容的指针,第三个参数是写入的数量:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h> //调用写入函数需要包涵这个头文件
#include <string.h> //调用strlen函数
int main()
{
int fd;
char *buf = "Hello Linux!"; //对该指针写入字符串
fd = open("new3",O_RDWR);
if(fd > 0)
{
printf("file open success\n");
}
else
{
open("new3",O_RDWR|O_CREAT,0600);
printf("file has been created!\n");
}
write(fd, buf, strlen(buf));
close(fd); //关闭文件
return 0;
}
2.2.读取文件大小
读取上一小节所写入的大小使用ssize_t read(int fd, void *buf, size_t count);函数,它的返回值和参数和写入函数差不多,第二个参数是定义一个指针来存放写入的数据:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h> //调用读取文件函数需要调用该头文件
#include <string.h>
#include <stdlib.h> //调用malloc函数
int main()
{
int fd, n_write, n_read;
char *buf = "Hello Linux!";
char *readBuf;
readBuf = (char *)malloc(sizeof(char) * n_write); //为该指针申请n_write个char的大小内存
fd = open("new3",O_RDWR);
if(fd > 0)
{
printf("file open success\n");
}
else
{
open("new3",O_RDWR|O_CREAT,0600);
printf("file has been created!\n");
}
n_write = write(fd, buf, strlen(buf));
close(fd); //写完数据之后需要关闭文件,否则读取的时候会出错,
//因为写完数据之后,光标的指向是指向数据的末尾,如果再进行读取就会读到空的内容
//因此需要关闭文件,让光标指向数据的开始
fd = open("new3",O_RDWR);
n_read = read(fd, readBuf, n_write);
printf("This file have %d byte\n", n_read);
return 0;
}
1527

被折叠的 条评论
为什么被折叠?



