您的位置:首页 > 运维架构 > Linux

Linux系统调用 - 文件操作

2012-12-16 21:07 441 查看
系统调用方式创建文件 -
测试程序一: test.c


#include<stdio.h>

#include<stdlib.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

void create_file(char *filename){

if(creat(filename, 0755)<0){ //创建一个文件赋予755权限

printf("create file %s failure!\n", filename);

exit(EXIT_FAILURE);

}else{

printf("create file %s success!\n", filename);

}

}

int main(int argc, char *argv[]){ //argc:参数的个数,argv数组:参数的名称数组,例如命令:hello
liu,有两个参数,一个是hello命令,一个是liu,所以argc为2

int i;

if(argc<2){ //
argc小于2,即为没有参数跟在命令后面

perror("you haven't input the filename, please try again!\n");

exit(EXIT_FAILURE);

}

for(i=1; i<argc; i++){ //
从1开始,即命令之后的参数名开始

create_file(argv[i]); //调用create_file函数

}

exit(EXIT_SUCCESS);

}

系统调用方式创建文件 - 测试程序二:test.c

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

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

int i;

if(argc < 2){

perror("please input the filename.\n");

exit(EXIT_FAILURE);

}

for(i = 1; i < argc; i++){

creat(argv[i], 0755);
//
创建文件,赋予755权限

}

}

系统调用 -
打开文件


int open(const char *pathname, int flags) //
打开pathname所对应的文件,flags是打开标志,返回一个整数类型值,为所打开文件的文件描述符

int open(const char *pathname, int flags, mode_t_mode) //mode_t_mode是使用O_CREAT的时候才会用到,表示创建新文件的相应默认权限

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <fcntl.h>

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

int fd;

if(argc < 2){

puts("please input the open file.\n");

exit(1);

}

if((fd=open(argv[1],O_CREAT|O_RDWR,0755))<0){ //
用fd获得打开文件相应的文件描述符,如果后面跟参数/文件名不存在,即使用O_CREAT去创建权限为0755的相应文件。

perror("open file failure.\n");

exit(1);

}

else{

printf("open file %d success.\n", fd);

}

close(fd); //
关闭fd文件描述符所对应的文件

exit(0);

}

系统调用 -
关闭文件


close(fd);
// 关闭fd所对应的文件

系统调用 -
读取文件read


int read(int fd, const void *buf, size_t length)

功能:从文件描述符fd所对应的文件之中读取length个字节到buf所指定的缓冲区之中,返回值为实际读取的字节数。

int write(int fd, const void *buf, size_t length)

功能:将buf所对应的缓冲区之中的length个字节写入fd所对应的文件,返回实际所写入的字节数。

系统调用 -
定位


int lseek(int fd, offset_t offset, int whence)

功能:将文件读写指针相对whence移动offset个字节。操作成功时返回相对于文件头的偏移。

offset:表示移动的位数,向前移动为负值,向后为正。 -3表示向前移动3个字节。

whence:
基准点

SEEK_SET相对文件头

SEEK_CUR相对文件读写指针的当前位置

SEEK_END相对文件尾

如: lseek(fd, -5, SEEK_CUR)
表示将fd所代表文件的文件指针基于当前的位置向前移动5个字节。

问:如何利用lseek计算文件的长度?

直接移动基于文件尾移动0位即可,其返回的值即为相对于文件尾所对应的长度。

leek(fd, 0,
SEEK_END)

系统调用 -
权限判断


int access(const char *pathname, int mode)

pathname:
文件名称

mode:
要判断的权限。

R_OK:
文件可读

W_OK:
文件可写

X_OK:
文件可执行

F_OK:
文件存在

如果测试成功则返回0,否则一个条件不符合则返回-1

#include <unistd.h>

#include <stdio.h>

int main(){

if(access("/root/c_code/test/t", F_OK) == 0){

printf("the file could be executable.\n");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: