[Detailed explanation of basic operations of common Linux file programming]

Detailed explanation of basic operations of common Linux file programming



foreword

The following is a simple demonstration of open, read, write, and close files under
linux and open, read, write, and close files under linux. Open read write lseek close under
linux


An overview of file programming

File operations under linux can be generally divided into three categories: open, read, and write. Other related operations are implemented based on opening, reading, and writing. The following will also use specific demos to implement the input of different parameters. Of course, There are many other small details that need to be paid attention to in the file operation, such as the permissions when opening the file, the meaning of various parameters, and so on.
In the following demo, not all situations are implemented. You can conduct different experiments according to yourself, and all operations are similar.
When using different functions, we can check the man manual under linux. For me, I don’t deliberately remember each function, just master some simple ones. We are checking the others when using them. Understand the meaning of each parameter, and then experiment with different small demos.

insert image description here

2. File opening and creation

Prototype of each operation function
int open(const char *pathname, int flags);
int close(int fd);

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(void)
{
    
    
	int fd = 0;    //文件返回描述符
	fd = open("./text",O_RDWR);  //在当前目录下以可读可写的方式打开
	if(fd == -1)  //打开失败返回-1 成功返回一个文件流
	{
    
    
		printf("open error\n");
		//可读可写 如果没有存在text文件则创建一个  0600 表示可读可写 4(可读) 2(可写) 1(可执行)
		fd = open("./text",O_RDWR |  O_CREAT,0600);  
		if(fd > 0)
		{
    
    
			printf("creat file success\n");
		}
	}
	else
	{
    
    
		printf("open success\n");
	}
	close(fd); //操作完成关闭文件描述符
	return 0;
}
}

operation result
insert image description here

3. Writing and reading files

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main(void)
{
    
    
	int fd = 0; //接收文件描述符 
	char writebuf[]="xiao yin student";
	char readbuf[128] = {
    
    0}; //读取缓冲
	int n_write = 0,n_read = 0; //读写大小返回

	fd = open("./text",O_RDWR); //以可读可写方式打开当前目录下text文件
	if(fd == -1)
	{
    
    
		printf("open error\n");
	}

	printf("fd = %d\n",fd); //将文件返回描述符打印出来
	n_write = write(fd,writebuf,sizeof(writebuf)); //接内容写入
	if(n_write != -1)
	{
    
    
		printf("write %d byte to file\n",n_write);
	}
	
	n_read = read(fd,readbuf,n_write); //将文件读取到readbuf
	if(n_read != -1)
	{
    
    
		printf("read %d byte to readbuf\n",n_read);
		printf("readbuf = %s\n",readbuf);
	}
	close(fd); //关闭

	return  0;
}

insert image description here

It can be seen from the results of the above experiment that it is different from what we imagined. This is because when we write the contents of the file for the first time, the cursor of the file has moved to the end, but when we read it next time, it is still Read from that end, so what we wrote won't be read at all. In the next demo, we will explain the cursor movement, and you can view the results of this experiment again.

5. Move the file cursor to the operation

The prototype
of the cursor function is only used here, and you can check the parameters yourself

insert image description here

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main(void)
{
    
    
	int fd = 0; //接收文件描述符 
	char writebuf[]="xiao yin student";
	char readbuf[128] = {
    
    0}; //读取缓冲
	int n_write = 0,n_read = 0; //读写大小返回

	fd = open("./text",O_RDWR); //以可读可写方式打开当前目录下text文件
	if(fd == -1)
	{
    
    
		printf("open error\n");
	}

	printf("fd = %d\n",fd); //将文件返回描述符打印出来
	n_write = write(fd,writebuf,sizeof(writebuf)); //接内容写入
	if(n_write != -1)
	{
    
    
		printf("write %d byte to file\n",n_write);
	}
	
	//写完注意重新将光标置到开头,或者关闭重新打开 要不然读取不到数据
	//close(fd);
	//fd = open("./text",O_RDWR); 

	//将光标重新置到开头
	lseek(fd,0,SEEK_SET);
	n_read = read(fd,readbuf,n_write); //将文件读取到readbuf
	if(n_read != -1)
	{
    
    
		printf("read %d byte to readbuf\n",n_read);
		printf("readbuf = %s\n",readbuf);
	}
	close(fd); //关闭

	return  0;
}

insert image description here

Six, file operation applet cp instruction implementation

Under Linux, we will often use the cp copy instruction, so how to implement this instruction, let's demonstrate with a simple demo.
Next, we will also use function parameter transfer, which will be used frequently in our learning later.

#include <stdio.h>
#include <error.h>
#include <unistd.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>



int main(int argc,char *argv[])
{
    
    
	char *ReadBuf = NULL;
	int src = 0,des = 0;  //源文件和目标文件的描述符
	int file_size = 0; //文件读取的大小存储

	//判断传入参数是否正确
	if(argc != 3)
	{
    
    
		perror("param error\n");
		exit(-1);
	}

	src = open(argv[1],O_RDWR); //以可读可写的 方式打开源文件
	if(src == -1) //打开失败
	{
    
    
		printf("src file open failed\n");
	}
	//将源文件的内容读取到readbuf 缓冲区
	file_size = lseek(src,0,SEEK_END); //读取文件大小
	lseek(src,0,SEEK_SET); //将文件指针移值开头
	ReadBuf = (char *)malloc(file_size*(sizeof(char)) + 8); //开辟缓冲空间大小
	read(src,ReadBuf,file_size); //读取内容

	//打开目标文件
	des = open(argv[2],O_RDWR |  O_CREAT,0600);
	if(des == -1)
	{
    
    
		perror("des file open failed\n");
	}
	//将源文件内容读取到目标wenj
	write(des,ReadBuf,file_size);
 	//关闭源文件
	close(src);
	close(des);
	return 0;
}

insert image description here
insert image description here

7. Write integers and structures to files

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

struct Data
{
    
    
	int a;
	char str[24];
};


int main(void)
{
    
    
	int fd = 0;
	struct Data dat1 = {
    
    100,"hello linux"};
	struct Data dat2;
	fd = open("./text",O_RDWR | O_CREAT,0600);
	if(fd == -1)
	{
    
    
		printf("open error\n");
		exit(-1);
	}

	write(fd,&dat1,sizeof(struct Data));
	lseek(fd,0,SEEK_SET);
	read(fd,&dat2,sizeof(struct Data));
	printf("read data:%d %s\n",dat2.a,dat2.str);
	close(fd);
	return 0;
}

insert image description here

Eight, standard c library operation of files

There are also several common operations on files in the standard c library: fopen fwrite fread fseek fclose and open write read lseek clsoe under linux.

一、fopen fwrite fread fclose
函数原型
FILE *fopen(const char *pathname, const char *mode);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
int fclose(FILE *stream);

insert image description here

pathname: file name
mode: file operation permissions

#include <stdio.h>
#include <string.h>


int main(void)
{
    
    
	//FILE *fopen(const char *pathname, const char *mode);
	FILE *fp;
	char str[] = "my linux test";
	char readbuf[128]= {
    
    0};
	fp = fopen("./text","w+");
	if(NULL == fp)
	{
    
    
		printf("fopen error\n");
	}
	//size_t fwrite(const void *ptr, size_t size, size_t nmemb,
    //                FILE *stream);
	//文件写入
	fwrite(str,sizeof(char),strlen(str),fp);
	//将光标置到开始位置
	fseek(fp,0,SEEK_SET);
	//文件读取
	// size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
	fread(readbuf,sizeof(char),strlen(str),fp);
	printf("read data:%s\n",readbuf);
	//关闭文件描述符
	fclose(fp);
	return 0;
}

insert image description here

二、fputc fgetc feof

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    
    
	FILE *fp;
	char c;
	fp = fopen("./text","w+");
	if(NULL == fp)
	{
    
    
		printf("fopen error\n");
		exit(-1);
	}
	// int fputc(int c, FILE *stream);

	//fputc('h',fp);
	while(!feof(fp)) //feof 到达文件尾不为0 
	{
    
    
		c = fgetc(fp);
		printf("c = %c",c);
	}
	fclose(fp);
	return 0;
}

Third, the structure is written to the standard c library file operation

#include <stdio.h>
#include <string.h>

struct Data
{
    
    
	int a;
	char name[24];
};

int main(void)
{
    
    
	//FILE *fopen(const char *pathname, const char *mode);
	struct Data dat = {
    
    100,"my linux"};
	struct Data dat2;
	FILE *fp;
	fp = fopen("./text","w+");
	if(NULL == fp)
	{
    
    
		printf("fopen error\n");
	}
	//size_t fwrite(const void *ptr, size_t size, size_t nmemb,
    //                FILE *stream);
	//文件结构体写入
	fwrite(&dat,sizeof(struct Data),1,fp);
	//将光标置到开始位置
	fseek(fp,0,SEEK_SET);
	//文件读取
	// size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
	fread(&dat2,sizeof(struct Data),1,fp);
	printf("read data:%d  %s\n",dat2.a,dat2.name);
	//关闭文件描述符
	fclose(fp);
	return 0;
}

insert image description here


Summarize

The file operations under Linux have been briefly demonstrated above. For these common operations, each of us needs to be proficient in using them, and we can learn more about the more complex operations (process threads, etc.) later. Well, come on.

Guess you like

Origin blog.csdn.net/boybs/article/details/123035245