Embedded knowledge points of Job Notes 04_0_IO system programming

Chapter 1 file IO in Linux

1, Basic introduction to file IO

1. Common file IO API s for Linux
open,close,write,read,lseek.

2. General steps of document operation
(1) open opens a file, obtains a file descriptor, reads and writes the file (or other operations), and finally close s the file.
(2) Files are usually block devices stored in the file system. We call this kind of files static files. When we open a file, the Linux kernel operations include: establishing a data structure of the open file in the process and recording the open file; Then apply for a section of memory to read the contents of the static file from the block device to a specific address in the memory for management and storage, which is called dynamic file.
(3) After the file is opened, the read and write operations for this file are all for this dynamic file. When we close the dynamic file, the kernel updates the dynamic file in memory to the static file in the block device.
(4) Common phenomenon: it is slow to open a large file; If the half written file is not saved, it will be shut down directly, and the file content will be lost after restart.

3. File descriptor

  • The file descriptor is actually a number that represents a specific meaning in the process. When we open a file, the operating system constructs some data structures in memory to represent the dynamic file, and then returns a number to the application as the file descriptor, that is, the identification of the file in the process.
  • The scope of the file descriptor is the current process. Out of the current process, the file descriptor is meaningless.
  • The legal range of file descriptor fd in Linux is 0 or a positive integer, which cannot be a negative number.

2, File IO function prototype

1.open function prototype

#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
Return value: the newly allocated file descriptor is returned successfully, and an error is returned-1 And set errno. 
  • Common options for flag (one of the first three constants must be specified, and only one is allowed to be specified):

    flag optionfunction
    O_RDONLYread-only
    O_WRONLYWrite only
    O_RDWRReading and writing
    O_CREATCreate a file
    O_EXCLCheck whether the file exists. If the file already exists, an error will be reported instead of re creation
    O_TRUNCOpen file overwrite
    O_APPENDOpen file append

    Open the device file in write blocking wait (O_SYNC) and non blocking (O_NONBLOCK) modes:

    • Blocking and non blocking: if a function is blocking, it may get stuck and wait when calling the function because the function execution conditions are not met. If it is non blocking, it will return immediately after calling this function, but it is uncertain whether the function has completed the task;
    • The blocking result is guaranteed but the time is not guaranteed, and the non blocking time is guaranteed but the result is not guaranteed
    • O_ During Nonblock, write only writes the content to the underlying buffer and returns it. Then the underlying layer synchronizes the buf content to the hard disk at one time when appropriate. This design is to improve the performance and efficiency of hardware operation and hardware life. But sometimes if we want the hardware not to wait for an immediate write, O is available_ SYNC.
  • open() permission to create files: Mode & (~ umask)
    For example:

    umask=0022 —>0777-0022=0755

    Therefore, before setting permissions, you should turn off the default permissions umask(0);.

2.close function prototype

#include <unistd.h>
int close(int fd)
Return value: 0 for success and 0 for error-1 And set errno. 

It should be noted that when a process terminates, the kernel calls close to close all the file descriptors of the process that have not been closed. Therefore, even if the user program does not call close, the kernel will automatically close all the files it opens when the process terminates.

3.write function prototype

#include <unistd.h>
ssize_t write(int fd, const void * buf, size_t count); 

Function Description: write()Will put the parameters buf Memory write referred to count Bytes to parameter fd Within the document referred to.
Return value: if successful write()The number of bytes actually written is returned( len). Returns when an error occurs-1,Error code storage errno Yes.

Additional notes:

  • The return value of the write() function generally has no 0. It will return 0 only when the following occurs: the third parameter in write(fp, p1+len, (strlen(p1)-len)) is 0. At this time, write() does nothing but returns 0;
  • When the write() function writes data from buf to fd, if the data in buf cannot be read at one time, the reading position pointer (that is, the second parameter buf) will not move automatically when reading the data in buf for the second time, which needs to be controlled by the programmer instead of simply filling the first address of buf into the second parameter. For example, the reading position movement can be realized in the following format: write (fp, p1+len, (strlen (P1)) -Len). In this way, when writing the second cycle, data will be written from p1+len to fp, and so on until (strlen(p1)-len) becomes 0;
  • Within the maximum data range that can be written at one time (looks like BUFSIZ, 8192), the third parameter count size should preferably be the size of the data in buf to avoid errors. (after the author's experiment again, there are not only 8192 that can be written at one time. The author tries to write 81920000 at one time, and the result is also OK. It seems that the maximum write data at one time is not 8192, but the BUFSIZ parameter does exist in the kernel, and the specific meaning remains to be studied).

4.read function prototype

#include <unistd.h>

ssize_t read(int fd, void * buf, size_t count);

Function Description: read()Will put the parameters fd File transfer count Bytes to buf In the memory indicated by the pointer.

Return value: the return value is the number of bytes actually read, If 0 is returned, Indicates that the end of the file has been reached or there is no readable data. If the parameter count Is 0, be read()It has no effect and returns 0. In addition, the return value is less than count. 
(1)When reading a regular file, when reading count The end of the file was reached before bytes. For example, if there are 50 bytes left from the end of the file and 100 bytes are requested to read, then read Return to 50, next time read Will return 0;
(2)For network socket interfaces, the return value may be less than count,But this is not a mistake. Refer to this article for a detailed explanation https://blog.csdn.net/hhhlizhao/article/details/73912578

Note: the read position pointer will not move automatically. However, if the file has been written before reading, the pointer will be behind. At this time, the written content cannot be read. At this time, it needs to be used in conjunction with lseek function.

5.lseek function prototype
Function purpose: adjust the position pointer of reading and writing.

#include <sys/types.h>
#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

Parameter Description: fd - File of current file inode;
          offfset - Offset, the distance moved by each read / write operation, in bytes. It can be positive or negative;
		  whence - The base point of the current position has three marks:
			①SEEK_SET: The beginning of the document;
			②SEEK_CUR: The current position of the file pointer;
			③SEEK_END: End of file.  
Return value:-1 Error in; current position of file pointer on success    

If you write several bytes of content to a file and then read it immediately, you can't read the content just written, because the file pointer has been moved to the back of the content by write.

3, File IO example

Implementation example of cp command

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>	
int main(int argc, char *argv[])
{
	int  rd_fd, wr_fd;
	char read_buf[128] = {0};
	char write_buf[128] = {0};
	int rd_ret = 0;

	if(argc <3)
	{
		printf("please input src file and des file \n");
		return -1;
	}

	rd_fd = open(argv[1],O_RDONLY);
	if(rd_fd < 0 )
	{
		printf("open src file %s failure\n",argv[1])
		return -2;
	}
	wr_fd =  open (argv[2],O_WRONLY);
	if(wr_fd <0)
	{
		printf("open des file %s failure\n",argv[2])
		return -3;
	}

	while(1)
	{
		rd_ret = read(rd_fd,read_buf,128);
		if(rd_ret < 128)
			break;
		write(wr_rd,read_buf,rd_ret);
		memset(wr_fd,read_buf,re_ret);
	}
	write(wr_rd,read_buf,rd_ret);

	close(rd_fd);	
	close(wr_fd);	
}

Chapter 2 standard IO in Linux

1, Basic introduction to standard IO

1. Difference between file IO and standard IO

  • (1) Concept

    • File IO: file I/O is called IO without cache. Without cache means that each read and write calls a system call in the kernel. The header file is unistd.h.
    • Standard IO is a standard I/O model established by ANSI C. It is a definition in standard function package and stdio.h header file, and has certain portability. Standard IO provides three types of cache: full cache, row cache and no cache.
  • difference

    • A significant difference between the two is that the standard I/O adopts the buffer mechanism by default. Standard IO is actually encapsulated by file IO. In fact, a buffer mechanism is added in the application layer. When file I/O reads and writes files, relevant system calls will be executed for each operation. The advantage of this processing is to directly read and write actual files, while the disadvantage is that frequent system calls will increase system overhead. Standard I/O can be regarded as encapsulating the buffer mechanism on the basis of file I/O. Read and write the buffer first, and then access the actual file if necessary, so as to reduce the number of system calls.
    • File I/O is mainly used for file operation, reading and writing hard disk, etc. it operates file descriptors; Standard I/O is aimed at the console, printout to the screen, etc. it operates the character stream. The characteristics of different devices are different, and different api access is the most efficient.

2. Standard IO API s commonly used in Linux

typeFile IO functionStandard IO function
openopenfopen
closeclosefclose
displacementlseekfseek,rewind
Reading and writingread,writeThere are many, including full cache, aviation cache and no cache
Read / write typeFile IO functionStandard IO function
readreadgetc,fgetc,getchar,
writewriteputc,fputc,putchar,fputs,puts,fwrite
  • File open / close: fopen, fclose
  • File read / write: fread, fwrite
  • Read / output string from file: fgets, fputs
  • Get and output characters: gets, puts
  • Get and output characters from the file: fgetc, fputc
  • The terminal outputs and inputs one character: getc, putc
  • Output and input one character: getchar, putcahr
  • Format I / O and slave files: fscanf, fprintf
  • From string: sscanf, sprintf
  • Slave terminal: scanf, printf
  • Flush buffer (full buffer, including buffer): fflush
  • Cursor positioning: fseek ftell, rewind
  • End of file: feof

3. Standard IO caching mechanism

  • Full buffer
    I/O operations can only be performed when the cache is full. Note that for files that reside on disk, full buffering is usually implemented by the standard IO library.

    Read: fread write: fwrite

  • row buffering
    I/O occurs only when a new line break is encountered \ nor when the cache is full. Note that when the flow involves terminals, line buffering is usually used.

    When a newline character (\ n) is encountered or the cache is full, the system call function: stdout is called
    Read: fgets,gets,printf,fprintf,sprintf
    Write: fputs,puts,scanf

  • No buffer
    Unbuffered means that the standard IO library does not buffer characters. Note that the standard error stream stderr is usually unbuffered.

    No cache stderr

2, Standard IO function prototype

1.fopen, fclose function prototype

Header file:#include <stdio.h>
Function prototype:
FILE *fopen(const char *path, const char *mode);
Return value: returned successfully FILE * Type pointer to the file you want to open;
        Failure Return NULL.          
      
Function parameters: const char *path  ----> Location of the open file 
		const char *mode  ----> file right
			"b"     Open file in binary mode
			"r"     To open a file as read-only, the file must exist
			"r+"    To open a file in a readable and writable manner, the file must exist
			"w"     Open the file in write only mode, empty it if it exists, and create it if it does not exist
			"w+"    Open the file in a readable and writable manner, empty it if it exists, and create it if it does not exist
			"a"     Append method. If the file does not exist, create a new one 
			"a+"    To read and append(Write at end of file),If the file does not exist, it is created.

Supplement:
The file permission (umask=0) created by fopen() function is 666, which is related to umask. By default, umask is 022666-022 = 644.

  • fclose
Function prototype:
int fclose(FILE *fp);
Return value: 0 returned successfully
		Failure Return feof()monitor

Function parameters: FILE *fp  File descriptor

Note: fclose will force the contents of the cache into the file, including the function of fflush.

2.fputs, fgets, fflush function prototype

  • fputs fgets: read / write function of row cache
//Read the data of size bytes from the file stream and put it into the pointer s
char *fgets(char *s, int size, FILE *stream);
Return value: if successful, return the first address pointer of the read string s;Otherwise, if it is at the end of the file or an error occurs null

int puts(const char *s, FILE *stream);
Return value: non negative value if successful;Otherwise, if there is an error; otherwise EROF -1
  • fflush: flush buffer
int fflush(FILE *stream);

fflush(stdin) refreshes the standard input buffer and discards the things in the input buffer [non-standard], which is generally not used;
fflush(stdout) is a line buffer, which refreshes the standard output buffer and prints the things in the output buffer to the standard output device;
stderr has no cache and will be written directly to the kernel.

Note: read and write operations also have position pointers

3. Prototype of gets and puts functions
gets, puts function reference link

gets, puts: read and write functions of row cache.

char *gets(char *s);  
int puts(const char *s);

Differences between gets and fgets:

  • gets() cannot specify the length of the cache, which is likely to cause the cache to be out of bounds (if the line is longer than the cache length) and written to the storage space after the cache, resulting in unpredictable consequences;
  • Another difference is that gets() does not store new line characters in the cache, and fgets stores new line characters in the cache.

Differences between puts and fputs:

  • Put() can only write to standard output;
  • A new line character will be added when putting () is output, and fputs will not.

4. Prototype of fseek, rewind and ftell functions
fseek, rewind, ftell function reference link

Adjust the read and write position of the file.

int fseek(FILE *stream, long offset, int whence);
Return value: 0 returned successfully
		Failure Return-1  
be careful: lseek and fseek The input parameters of the function are the same, but the return values are different
 Parameters: FILE *stream  FILE * file
		long offset   Offset
		int whence    Offset position
		SEEK_SET  Beginning of file
		SEEK_CUR  Current location
		SEEK_END  End of file   

long ftell(FILE *stream);
Return value: successfully returns the number of bytes from the current location of the file to the beginning of the file
		Failure Return-1
			 
void rewind(FILE *stream);//Set the offset of the file to the starting position, and the function does not return a value

example:

fseek(filep1,0,SEEK_SET);//Set the offset of the file to the starting position
long ftell(filep1);amount to fseek(filep1,0,SEEK_END);
void rewind(filp1)//Equivalent to fseek(filep1,0,SEEK_SET)

5.fprintf, fscanf, sprintf, sscanf, printf function prototype

printf can only be output to the display.

1) fprintf: It can be output to a file or to the display.
int fprintf(FILE *stream, const char *format, ...);
Parameters:
	FILE *stream        FILE *  file name
	const char *format  character string
	...
example: fprintf(filep,"hello%s%d%.2f\n",buf,year,d);

2) sprintf: Output content to a string.
int sprintf(char *str, const char *format, ...);
//Splicing strings in the format you specify is more powerful than strcat
 Parameters:
	char *str           String splice specified position
	const char *format  String format
	... 
example: sprintf(buf0,"%sworld-%d-%d-%d",buf,year,month,day);

3)  int fscanf(FILE *stream, const char *format, ...);
Parameters: FILE *stream        FILE *  file name
	const char *format  character string
	... Add content to the file

4) int sscanf(const char *str, const char *format, ...);
	//Split the string in the format you specify
 Parameters:
	char *str           String split specified location
	const char *format   String format
	... 
example: sscanf(time,"%d-%d-%d",&year,&month,&day);//Address visited&

6.fputc, fgetc, getc, putc function prototype
fgets,fputs,fputc,fgetc summary

fputc fgetc: a character read / write function.

int fgetc(FILE *stream);//Read a character from the file, which is equivalent to fread(buf,1,1,stream);
Return value: the value of the character you read ASCII code

int fputc(int c, FILE *stream);//Write a character to the file 
Parameter Description: the first parameter is the character to be written, and the second parameter is the file stream.
Return value: if successful, the entered characters will be returned, and an error will occur EOF. 

int getc(FILE *stream);//Read a character from the file 
Return value: the value of the character you read ASCII code

int putc(int c, FILE *stream);//Write a character to the file  

be careful:
fputc can also read in newline characters; fputc has a cache, but it is not a row cache function.
Think about how to pass code verification???

7.getchar and putchar function prototype
Calling getchar() is equivalent to calling fgetc(stdin).
Call putchar © Equivalent to calling fputc(c, stdout)

#include <stdio.h>

int getchar(void);//Carriage return character of monitoring buffer     
int putchar(int c);  //Print character 

8. Prototype of feof, ferror and clearerr functions
feof, ferror, clearerr function reference links

feof determines whether the end of the file has been reached;
ferror determines whether there is a read-write error;
clearerr clear stream error.

int feof(FILE *stream);
Function function: judge whether it has reached the end of the file.
Return value: when the end of the file is reached, a non-zero value is returned; 0 if no

int ferror(FILE *stream);
Function function: judge whether there is a read-write error.

int clearerr(FILE *stream);
Function function: clear stream error.

9.fstat function prototype
Get file properties.

Header file:#include <sys/stat.h>

int fstat(int fildes, struct stat *buf);
Return value: 0 returned successfully
		Failure Return-1
 Parameters:
	int fildes  The file descriptor of the file for which you want to get the properties
	struct stat *buf Store the file properties you obtained

10. Prototype of FREAD and fwrite functions
Full cache read and write of files.

Header file:#include <stdio.h>

Function prototype:
	size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Function parameters: void *ptr     ----> Storage space name
			size_t size   ---->Size of each data block unit: bytes
			size_t nmemb  ---->How many data blocks are you going to read
			FILE *stream  ---->File type FELE *File pointer for
 Return value: successfully returns the number of read complete data blocks
		Failure returns 0 or less than
		Judge whether the file has been read. Don't judge with the return value. Use a new method feof()judge

	size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

fwrite has a cache, not a row cache, but a full cache.

3, Standard IO example

1. Implement cat

#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"
#include "string.h"
int main(int argc, char** argv)
{
	FILE *src_fp;
	int read_ret;
	if(argc < 2)
	{
		printf("please input src file\n");
		return -1;
	}

	src_fp=fopen(argv[1],"r");
	if(src_fp ==NULL)
	{
		printf("open src file %s failure\n",argv[1]);
		return -1;
	}
	printf("open drc file %s sucess\n",argv[1]);

	// start read write
	while(1)
	{
		read_ret = fgetc(src_fp);
		if(feof(src_fp))
		{
			printf("read file %s end\n",argv[1]);
			break;
		}
		fputc(read_ret,stdout); 
	}
	fclose(src_fp);
	return 0;
}

2. Compare the efficiency of read / write and fgetc / fputc
File io

// read.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char **argv)
{
	int src_fd,des_fd;
	int read_ret=0;
	char buf[128]={0};
	if(argc <3)
	{
		printf("please input src and des file\n");
		return -1;
	}
	src_fd = open(argv[1],O_RDONLY);
	if(src_fd<0)
	{
		printf("open src file %s failure\n",argv[1]);
		return -2;
	}
	printf("open src file %s sucess\n",argv[1]);

	des_fd=open(argv[2],O_CREAT | O_WRONLY,0777);
	if(des_fd<0)
	{
		printf("open des file %s failure\n",argv[2]);
		return -3;
	}
	printf("open des file %s sucess\n",argv[2]);

	//start resd write
	while(1)
	{
		read_ret=read(src_fd,buf,128);
		write(des_fd,buf,read_ret);
		if(read_ret<128)
		{
			printf("raed file %s end!\n",argv[1]);
			break;
		}
	}
	write(des_fd,buf,read_ret);
	close(src_fd);
	close(des_fd);	

	return 0;
}

Standard io function

//fgetc.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char **argv)
{
	FILE *src_fp,*des_fp;
	int read_ret=0;
	if(argc <3)
	{
		printf("please input src and des file\n");
		return -1;
	}
	src_fp = fopen(argv[1],"r");
	if(src_fp==NULL)
	{
		printf("open src file %s failure\n",argv[1]);
		return -2;
	}
	printf("open src file %s sucess\n",argv[1]);

	des_fp=fopen(argv[2],"w");
	if(des_fp==NULL)
	{
		printf("open des file %s failure\n",argv[2]);
		return -3;
	}
	printf("open des file %s sucess\n",argv[2]);

	//start resd write
	while(1)
	{
		read_ret=fgetc(src_fp);
		fputc(read_ret,des_fp);
		if(feof(src_fp))
		{
			printf("raed file %s end!\n",argv[1]);
			break;
		}
	}
	fclose(src_fp);
	fclose(des_fp);	

	return 0;
}
typeread/writefgetc/fputc
real0.131s0.533s
user0.016s0.366s
sys0.115s0.134s

3. Compare the efficiency of fgets/fputs and fread/fwrite

//fgets.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char **argv)
{
	FILE *src_fp,*des_fp;
	int read_ret=0;
	char readbuf[128]={0};
	if(argc <3)
	{
		printf("please input src and des file\n");
		return -1;
	}
	src_fp = fopen(argv[1],"r");
	if(src_fp==NULL)
	{
		printf("open src file %s failure\n",argv[1]);
		return -2;
	}
	printf("open src file %s sucess\n",argv[1]);

	des_fp=fopen(argv[2],"w");
	if(des_fp==NULL)
	{
		printf("open des file %s failure\n",argv[2]);
		return -3;
	}
	printf("open des file %s sucess\n",argv[2]);

	//start resd write
	while(1)
	{
		fgets(readbuf,128,src_fp);
		fputs(readbuf,des_fp);
		if(feof(src_fp))
		{
			printf("raed file %s end!\n",argv[1]);
			break;
		}
	}
	fclose(src_fp);
	fclose(des_fp);	

	return 0;
}
//fread.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char **argv)
{
	FILE *src_fp,*des_fp;
	int read_ret=0;
	char readbuf[128]={0};
	if(argc <3)
	{
		printf("please input src and des file\n");
		return -1;
	}
	src_fp = fopen(argv[1],"r");
	if(src_fp==NULL)
	{
		printf("open src file %s failure\n",argv[1]);
		return -2;
	}
	printf("open src file %s sucess\n",argv[1]);

	des_fp=fopen(argv[2],"w");
	if(des_fp==NULL)
	{
		printf("open des file %s failure\n",argv[2]);
		return -3;
	}
	printf("open des file %s sucess\n",argv[2]);

	//start resd write
	while(1)
	{
		read_ret=fread(readbuf,1,128,src_fp);
		fwrite(readbuf,1,read_ret,des_fp);
		if(read_ret<128)
		{
			printf("raed file %s end!\n",argv[1]);
			break;
		}
	}
	fwrite(readbuf,1,read_ret,des_fp);
	fclose(src_fp);
	fclose(des_fp);	

	return 0;
}

typeRead / write (example in the previous section)Fgetc / fputc (example in the previous section)fgets/fputsfread/fwrite
real0.131s0.533s0.059s0.049s
user0.045s0.366s0.006s0.011s
sys0.087s0.134s0.052s0.008s

Therefore, the efficiency is FREAD / fwrite > fgets / fputs > fgtec / fputc.

Chapter III directory IO

1, Basic introduction to directory IO

1. Header file and common IO API

  • Header file
    #include <sys/types.h>
    #include <dirent.h>
    
  • Comparison of directory IO and file IO

2, File IO function prototype

1.mkdir function prototype
Create a new directory.

#include <sys/stat.h>
Function prototype:
	int mkdir(const char *path, mode_t mode);
Parameters:
	const char *path  ---->Directory file path to create
	mode_t mode      ---->Permissions for new files 0777

Note: the generated directory permissions are still related to umask. The default umask=0022

2.opendir and closedir function prototype
Open and close the directory.

#include <sys/types.h>
#include <dirent.h>
Function prototype:
	DIR *opendir(const char *name);
Return value:
	Successful return DIR The pointer of type points to the directory you open
	Failure Return NULL
 Parameters:
	const char *name Full directory path
 Return value:
	The directory stream pointer is returned successfully, and an error is returned NULL. 

int closedir(DIR *dirp);//Structure pointer

3.readdir function prototype
Reading of directory.

#include <dirent.h>

struct dirent *readdir(DIR *dirp);
Return value: if successful; otherwise struct dirent Pointer, if it is at the end of the directory or there is an error, it returns NULL. 

dirent The structure is defined in the header file dirent.h Medium:
struct dirent {
		ino_t          d_ino;       /* Node number*/
		off_t          d_off;       /* The next offset of the directory */
		unsigned short d_reclen;    /* Directory size*/
		unsigned char  d_type;      /* Directory type*/
		char           d_name[256]; /* Directory name */
};//It stores the relevant information of each file in the directory

file type d_type Judgment:
	DT_BLK      This is a block device. //Block device file

	DT_CHR      This is a character device.//Character device file

	DT_DIR      This is a directory.//Catalog file

	DT_FIFO     This is a named pipe (FIFO).//Pipeline file

	DT_LNK      This is a symbolic link.//Soft link file

	DT_REG      This is a regular file.//Ordinary asking price

	DT_SOCK     This is a UNIX domain socket.//s socket 

	DT_UNKNOWN  The file type is unknown.//Unknown type

4.rewinddir function prototype
Reset the position of the read directory stream to the beginning

void rewinddir(DIR *dr);  
Parameters: Directory stream pointer

5.telldir function prototype
Gets the position of the current position pointer

long telldir(DIR *dirp)  
Function Description: telldir()Return parameters dir Current read location of directory stream. This return value represents the offset from the beginning of the directory file. The return value returns the next read location, Returns when an error occurs-1.

6.seekdir function prototype
Can be located anywhere. Similar to the file locator function fseek(), set the location of the next readdir() operation on the directory stream.

void seekdir(DIR *dirp , long loc)   
Function Description: seekdir()Used to set parameters dir Current read location of directory stream, In call readdir()Start reading from this new location. parameter offset Represents the offset from the beginning of the catalog file

3, Directory IO example

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int main()
{
    DIR * dir;
    struct dirent * ptr;
    int i;
    dir = opendir("/etc/rc.d");
    while((ptr = readdir(dir))!= NULL)//Linked list traversal
    {
        printf("d_name : %s\n", ptr->d_name);
    }
    closedir(dir);
	return 0;
}

Comprehensive example

File upload and download in stand-alone mode
(1) Enter the address of the server: path and directory name
(2) List which files are in the server: opendir readdir
(3) Enter the name of the file downloaded from the server or uploaded to the server
(4) File download or transfer on file

File IO: open read write close
Standard IO fopen fputs fgets fputc fgetc fread fwrite fclose

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

int main(int argc,char **argv)
{
	DIR *dp;
	struct dirent * dir;
	char server[128]={0};
		
	int fd;
	char file[128]={0};
	int src_fd,des_fd;
	char buf[128]={0};
	int ret;

start:
	printf("please input server PATH and Directory name\n");
	scanf("%s",server);

	//list server fildes
	dp = opendir(server);
	if(dp==NULL)
	{
		printf("open server %s error\n",server);
		goto start;
	}
	printf("open server %s success\n",server);

	//read server dir
	while(1)
	{
		dir = readdir(dp);
		if(dir==NULL)
		{
			break;
		}
		else
		{
			printf("inode=%ld name =%s\n",dir->d_ino,dir->d_name);
		}
	}

	printf("please input download file name\n");
	scanf("%s",file);

	//open server file
	src_fd = open(strcat(strcat(server,"/"),file),O_RDONLY);
	if(src_fd<0)
	{
		printf("open download file %s failure\n",file);
		return -1;
	}
	printf("open download file %s success\n",file);

	des_fd=open(file,O_CREAT | O_WRONLY);
	if(des_fd < 0)
	{
		printf("create file %s error\n",file);
		return -2;
	}
	printf("create file %s success\n",file);

	while(1)
	{
		ret=read(src_fd,buf,128);
		write(des_fd,buf,ret);
		if(ret < 128){
			break;
		}
	}
	write(des_fd,buf,ret);
	close(des_fd);
	close(src_fd);
	closedir(dp);

	return 0;
}

Tags: Linux

Posted on Wed, 29 Sep 2021 15:59:26 -0400 by dinku33