Linux file operation example

Linux file operation example

There are two ways to operate Linux files, the c library function and the linux file api function. Here we mainly talk about the system api function. It is worth noting that the file write operation is written to the cache, not directly in the memory file, so it is necessary to update the file or Close file

linux system file api function
 header file
  #include <sys/types.h>
  ; #include <sys/stat.h>
  #include <fcntl.h>
function prototype
 create
  int creat(const char *filename, mode_t mode);
parameter filename File name string format
Mode permission
Return success 0 Failure -1

Open
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
parameter filename File name string form
 flags Open mode, read operation requires read mode, write operation requires write mode
  Mode permission
 return file number
read and write
int read(int fd, const void *buf, size_t length);
parameter
 fd file number
 buf read data array
 length to save data length to read length
 return actual read length  
 
int write(int fd, const void *buf, size_t length);
parameter
 fd file number
 buf read the data to save the data array
length data length
return success 0 failure -1

Close
int close(int fd);
parameter fd file number
return success 0 failure -1

File positioning
int lseek(int fd, offset_t offset, int whence);
File operation process
 Read operation process Open file-Read file-Close file
 Write operation process Open file-Write file-Close file
Program example

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void write_file(char *s)
{
    
    
	int fd;
	
	fd = open("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); //创建并打开文件
	if(fd > 0)//创建成功或者打开成功
	{
    
    
		write(fd, s, sizeof(s));
		close(fd);
	}
	else
	{
    
    
	
	}
}
int read_file(char *s,int len)
{
    
    
	int fd,rtn_len;
	
	fd = open("hello.txt", O_RDWR);
	rtn_len = read(fd, s, len); /* 读取文件内容 */
	close(fd);
	return rtn_len;
}
int main()
{
    
    
	char testbuf[100] = {
    
    0},len;
	//写操作
	write_file("hello guoguo\n");
	//读操作
	len = read_file(testbuf,100);
	testbuf[len] =/0;
	printf(%s”, testbuf)}

Guess you like

Origin blog.csdn.net/u010835747/article/details/105159350