“This is the 14th day of my participation in the August Text Challenge.

Predefined flow

Before the program starts, three file descriptors, standard input, standard output, and standard error output corresponding to 0, 1, and 2, are created, and three predefined stream Pointers are encapsulated on the basis of them

  1. Standard input: stdin —- keyboard file
  2. Standard output: stdout —- terminal file
  3. Stderr —- terminal file

Code:

int main(int argc, const char *argv[])
{
    //stdin
    char buf[123] = {0};
    fgets(buf,123.stdin);// Read data from the standard input stream
    printf("buf = %s\n",buf);
    // Standard output
    fprintf(stdout."hello world%s"."112123");
    // Standard error output
    fprintf(stderr."hello world%s"."112123");
    return 0;
}
Copy the code
linux@ubuntu:~/demo/test/IO/test$ ./a.out 
hello world
buf = hello world

hello world112123hello world112123linux@ubuntu:~/demo/test/IO/test$ 
Copy the code

The buffer

Interview Question: What is a buffer zone? Standard IO encapsulates a piece of data address on the basis of file IO (generally used to store data that is not urgent). When the buffer address is full, or the programmer manually refreshes the space, the data in the space will be called file IO operation.

Buffer zones fall into three categories:

The buffer

Generally, it is an operation on a file. The full buffer size is 4096 bytes.

(Tail -f + file name) : You can open another terminal to dynamically view file contents

Conditions for flushing buffers:

  1. Buffer full flush buffer

  2. The program finishes flushing the buffer

  3. The program flushes the buffer manually

fflush

  1. Prototype:int fflush(FILE *stream);
  2. Function: Refresh buffer
  3. Parameter: target file stream pointer
  4. The return value:
    1. Success: 0
    2. Returns: EOF

Test code:

int main(int argc, const char *argv[])
{
    FILE * fp = fopen("./1.txt"."w");
    // Fopen, open only for the moment when it is opened
    if (NULL ==fp)
    {
        perror("fopen");
        return - 1;
    }
    fprintf(fp,"hello world");
    fflush(fp);
    while(1);
    
    return 0;
}         
Copy the code

The line buffer

There are only two line buffers, standard input and standard output. The line buffer size is 1024 bytes

Conditions for refreshing row buffers:

  1. Flush the buffer if the buffer is full

  2. The buffer is flushed when it encounters \n

  3. When the standard input and standard output parties use the buffer, the party that is using the buffer needs to give it to the party that needs it

  4. Fflush flushes the buffer

  5. End of the program

Test code:

1. Verify the cache size

#include <stdio.h>
int main(int argc, const char *argv[])
{
    // The buffer size is 1024 bytes

    // Verify buffer size
    int i = 0;
    for ( i = 0; i < 1024; i++)
    {
        printf("1");// Input one byte at a time to standard output
    }
    while(1);// block
    
    return 0;
}

Copy the code
linux@ubuntu:~/demo/test/IO/test$./ a.ut ^C //1024 will not print linux@ubuntu:~/demo/test/IO/test$./ a.ut 1111111111...... 11111111111111 // Can be printed at 1025Copy the code

2. Validate ‘\n’ to flush the row cache

#include <stdio.h>
int main(int argc, const char *argv[])
{
    // Verify that '\n' flushes the cache
    int i = 0;
    for ( i = 0; i < 10; i++)
    {
        printf("1");// Input one byte at a time to standard output
    }
    printf(\n"");/ / refresh
    while(1);/ / blocking
    
    return 0;
}
Copy the code
linux@ubuntu:~/demo/test/IO/test$ ./a.out 
1111111111

Copy the code

3. Verify that standard I/O flushes the cache

#include <stdio.h>
int main(int argc, const char *argv[])
{
    // Verify that '\n' flushes the cache
    int i = 0;
    for ( i = 0; i < 10; i++)
    {
        printf("1");// Input one byte at a time to standard output
    }
    int n;
    scanf("%d",&n);
    /*printf("hello"); return 0; }Copy the code
linux@ubuntu:~/demo/test/IO/test$ ./a.out 
11111111112

linux@ubuntu:~/demo/test/IO/test$ ./a.out 
1111111111hellolinux@ubuntu:~/demo/test/IO/test$
Copy the code

4. Ffiush can also be used, so I will not use the code.

There is no buffer

It is usually standard error output, usually used for more urgent data, so it will not enter the buffer. Call file IO directly.

Common usage: fprintf(stderr,” Hello world”);

Use this method to avoid printf forgetting to write ‘\n’ without output;

Time function

1.time

  1. #include

  2. Prototype:

    time_t time(time_t *tloc);

    // If you want a pointer later, you can define a variable to take the address and place it here

    time_t mytime;
    time(mytime);
    
    struct tm *localtime(const time_t *timep); 
    struct tm * mytm = localtime(&mytime);
    Copy the code

    typedef long time_t

  3. Function: Get the number of seconds from the current computer time to 1970-01-00-00-00

  4. Parameters:

    Tloc: Address of the variable used to store the obtained description. This value can be filled with NULL. If NULL is filled, the number of seconds to obtain is obtained by returning the value

  5. The return value:

    1. The number of seconds from 1970-01-00-00-00 to the present was successfully returned
    2. Return :(time_t)-1 on failure

Code:

#include <stdio.h>
#include <time.h>
int main(int argc, const char *argv[])
{  
    time_t mytime;
    mytime = time(NULL);
    printf("The current time to 1970 is %ld\n",mytime);
    return 0;
}       
Copy the code
linux@ubuntu:~/demo/test/IO/test$./a.out The current time to 1970 is 1630154859 // Use seconds to calculate the timeCopy the code

2.ctime

  1. Prototype:char *ctime(const time_t *timep);
  2. Function: according to the fixed format will now convert the time out
  3. Argument: address of a variable of type time_t
  4. The return value:
    1. Success returns the first address of the wrapped string
    2. Returns NULL on failure
  5. Note: With ctime, the output format is fixed and cannot be changed by the user

Code:

#include <stdio.h>
#include <time.h>
int main(int argc, const char *argv[])
{  
	time_t mytime;
	mytime = time(NULL);// The time function gets the number of seconds
	printf("The current time to 1970 is %ld\n",mytime);
	// Convert the number of seconds to a fixed string using ctime
	char * buf = ctime(&mytime);
	printf("Now the time is %s",buf);
    return 0;
}  

Copy the code
linux@ubuntu:~/demo/test/IO/test$./a.out Current time to 1970 time 1630155367 current time Sat Aug 28 05:56:07 2021Copy the code

3.localtime

  1. Prototype:struct tm *localtime(const time_t *timep);
  2. Function: The timep will be converted to the present time, the data stored in the structure
  3. Parameter: address of the seconds variable
  4. The return value:
    1. Success: an encapsulated TM structure is returned
    2. Failure: NULL

Suruct TM structure:

struct tm {
	int tm_sec;    /* Seconds (0-60) A leap second is used for time calibration */
	int tm_min;    /* Minutes (0-59) */
	int tm_hour;   /* Hours (0-23) */
	int tm_mday;   /* Day of the month (1-31) */
	int tm_mon;    /* Month (0-11) +1 */ is required
	int tm_year;   /* year-1900 = 70 - + 1900-*/In ten thousand, insectint tm_wday;   /* Day of the week (0-6, Sunday = 0) */
	int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
	int tm_isdst;  /* Summer camp time */
};     
Copy the code

Code:

#include <time.h>

int main(int argc, const char *argv[])
{
    time_t mytime;
    mytime = time(NULL);// The time function gets the number of seconds

    // Call localtime to encapsulate tm structures
    struct tm * mytm = localtime(&mytime);
    if(NULL == mytm)
    {
        perror("localtime");
        return - 1;
    }
    printf("The current time is :%d year -%d month -%d day --%d:%d:%d\n",
    mytm->tm_year+1900,mytm->tm_mon+1,mytm->tm_mday,
    mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
    return 0;
}
Copy the code

📝 exercise: write log file, write time to file every 1 second, sleep (1)

#include <stdio.h>
#include <time.h>
int main(int argc, const char *argv[])
{
    // Open a file
    FILE *fp = fopen("./1.txt"."a");
    if(NULL == fp)
    {
        perror("fopen");
        
        return - 1;
    }
    while(1)
    {
        // Get the current distance from 1970 in seconds
        time_t mytime = time(NULL);
        // Start converting time
        struct tm * mytm = localtime(&mytime);
        fprintf(fp,"The current time is :%d year -%d month -%d day --%d:%d:%d\n",
        mytm->tm_year+1900,mytm->tm_mon+1,mytm->tm_mday,
        mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
        fflush(fp);
        sleep(1);
    }
    return 0;
} 
Copy the code

statGets the file status property

  1. The header file:
    1. #include <sys/types.h>
    2. #include <sys/stat.h>
    3. #include <unistd.h>
  2. Prototype:int stat(const char *pathname, struct stat *statbuf);
  3. Run the following command to obtain the status of a file
  4. Parameters:
    1. Pathname: indicates the path and name of the target file
    2. Statbuf: structure address for storing file attribute information
  5. The return value:
    1. Returns 0 on success
    2. Failure returns: -1

The stat structure

struct stat {
	dev_t     st_dev;         /* Device file ID */
	ino_t     st_ino;         /* Inode A file number */
	mode_t    st_mode;        /* File type and permissions */
	nlink_t   st_nlink;       /* Number of links */
	uid_t     st_uid;         /* Owning user ID */
	gid_t     st_gid;         /* Group ID */
	dev_t     st_rdev;        /* Character device file ID */
	off_t     st_size;        /* File size */
	blksize_t st_blksize;     /* Block size for filesystem I/O */
	blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */
	struct timespec st_atim;  /* Last access time */
	struct timespec st_mtim;  /* Last modified time */
	struct timespec st_ctim;  /* Last state change */

	#define st_atime st_atim.tv_sec      /* Backward compatibility */
	#define st_mtime st_mtim.tv_sec
	#define st_ctime st_ctim.tv_sec
};
           
struct timespec {
	time_t      tv_sec;     / * seconds * /
	long        tv_nsec;    / * ns * /
};
Copy the code

Type of file

st_mode

r W X R W x R W X
8 7 6 5 4 3 2 1 0
host Team members other
876 543 210

The file type defines the following mask values:

St_mode has file information, which corresponds to 0170000.

S_IFMT     0170000   bit mask for the file type bit field

S_IFSOCK   0140000   socket
S_IFLNK    0120000   symbolic link
S_IFREG    0100000   regular file
S_IFBLK    0060000   block device
S_IFDIR    0040000   directory
S_IFCHR    0020000   character device
S_IFIFO    0010000   FIFO
Copy the code

File permissions define the following mask values:

S_ISUID     04000   set-user-ID bit
S_ISGID     02000   set-group-ID bit (see below)
S_ISVTX     01000   sticky bit (see below)

S_IRWXU     00700   owner has read, write, and execute permission
S_IRUSR     00400   owner has read permission
S_IWUSR     00200   owner has write permission
S_IXUSR     00100   owner has execute permission

S_IRWXG     00070   group has read, write, and execute permission
S_IRGRP     00040   group has read permission
S_IWGRP     00020   group has write permission
S_IXGRP     00010   group has execute permission

S_IRWXO     00007   others  (not  in group) have read, write, and execute permission
S_IROTH     00004   others have read permission
S_IWOTH     00002   others have write permission
S_IXOTH     00001   others have execute permission
Copy the code

📝 Print the file type and permission

Code:

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <pwd.h> 
#include <grp.h> 
#include <time.h>

int main(int argc, const char *argv[])
{
    struct stat mystat;

    if(stat(argv[1],&mystat) == - 1)
    {
        perror("stat");
        return - 1;
    }
    // Start printing the type of file
    switch (mystat.st_mode & S_IFMT)
    {
    case S_IFSOCK:
        printf("s");
        break;
    case S_IFLNK:
        printf("l");
        break;
    case S_IFREG:
        printf("-");
        break;
    case S_IFBLK:
        printf("b");
        break;
    case S_IFDIR:
        printf("d");
        break;
    case S_IFCHR:
        printf("c");
        break;
    case S_IFIFO:
        printf("p");
        break;
    }

    // Permission to start printing files
    if((mystat.st_mode & S_IRUSR) ! =0)
    {
        printf("r");
    }else{
        printf("-");
    }
    if((mystat.st_mode & S_IWUSR) ! =0)
    {
        printf("w");
    }else{
        printf("-");
    }
    if((mystat.st_mode & S_IXUSR) ! =0)
    {
        printf("x");
    }else{
        printf("-");
    }
    // Start judging group permissions
    if((mystat.st_mode & S_IRGRP) ! =0)
    {
        printf("r");
    }else{
        printf("-");
    }
     if((mystat.st_mode & S_IWGRP) ! =0)
    {
        printf("w");
    }else{
        printf("-");
    }
    if((mystat.st_mode & S_IXGRP) ! =0)
    {
        printf("x");
    }else{
        printf("-");
    }
    // Start judging other user permissions
     if((mystat.st_mode & S_IROTH) ! =0)
    {
        printf("r");
    }else{
        printf("-");
    }
     if((mystat.st_mode & S_IWOTH) ! =0)
    {
        printf("w");
    }else{
        printf("-");
    }
    if((mystat.st_mode & S_IXOTH) ! =0)
    {
        printf("x");
    }else{
        printf("-");
    }
    printf("\n");
    
    return 0;
}
Copy the code
linux@ubuntu:~/demo/test/IO/test$ ./a.out test.c 
-rwxrwxrwx  
Copy the code

User information

  1. The header file:
    1. #include <sys/types.h>
    2. #include <pwd.h>
  2. Prototype:struct passwd *getpwuid(uid_t uid);
  3. Function: Query user information by ID number and encapsulate structure
  4. Parameter: User ID number
  5. The return value:
    1. Returns the encapsulated structure passwd successfully
    2. Return NULL on failure
struct passwd {
	char   *pw_name;       /* username */
	char   *pw_passwd;     /* user password */
	uid_t   pw_uid;        /* user ID */
	gid_t   pw_gid;        /* group ID */
	char   *pw_gecos;      /* user information */
	char   *pw_dir;        /* home directory */
	char   *pw_shell;      /* shell program */
};   
Copy the code

Set of information

  1. The header file:
    1. #include <sys/types.h>
    2. #include <grp.h>
  2. Struct group *getgrgid(gid_gid);
  3. Parameter: Group ID
  4. The return value:
    1. Returns the encapsulated structure address successfully
    2. Return NULL on failure
struct group {
	char   *gr_name;        /* group name */
	char   *gr_passwd;      /* group password */
	gid_t   gr_gid;         /* group ID */
	char  **gr_mem;         /* A null-terminated array containing the member names */
};        
Copy the code

Code:

   // Add the following code

	/ / link count
    printf(" %ld ",mystat.st_nlink);

    // Prints the user name

    struct passwd * mypass = getpwuid(mystat.st_uid);
    if(NULL ==mypass)
    {
        perror("getpwuid");
        return - 1;
    }

    printf("%s ",mypass->pw_name);
    // Prints the group name
    struct group * mygr = getgrgid(mystat.st_gid);
    if (NULL ==mygr)
    {
        perror("getgrgid");
        return - 1;
    }
    // Prints the group life
    printf("%s ",mygr->gr_name);
    // Print size
    printf("%ld",mystat.st_size);
    // Print time
    struct tm * mytm = localtime(&mystat.st_ctim.tv_sec);
    printf("%d month %d %02d:%02d",mytm->tm_mon+1,mytm->tm_mday,mytm->tm_hour,mytm->tm_min);
    printf("%s\n",argv[1]); 
Copy the code
linux@ubuntu:~/demo/test/IO/test$./a.out test.c -rwxrwxrwx 1 Linux Linux 2537 8月 28 07:31test.cCopy the code

Directory operations

opendir

  1. The header file:
    1. #include <sys/types.h>
    2. #include <dirent.h>
  2. Prototype:
    1. DIR *opendir(const char *name);
    2. DIR: directory flow pointer —– Flag to open a directory for future use
  3. Parameter: name: path of the directory to be opened
  4. Return value:
    1. The directory flow pointer was returned successfully
    2. Return NULL on failure

readdir

  1. Header file: #include

  2. Struct dirent *readdir(DIR *dirp);

  3. Function: Read directory files

  4. Parameter: target directory stream pointer

  5. The return value:

    1. Success returns the address of an encapsulated directory information structure
    2. Return NULL on failure
    3. Return NULL after reading to end of file
  6. Note: all file information cannot be read at the same time. Each read returns a wrapped structure.

struct dirent {
ino_t          d_ino;       /* the Inode number is used for indexing lists -- the number of files */
off_t          d_off;       /* File offset */
unsigned short d_reclen;    /* The length of the file name */
unsigned char  d_type;      /* The type of file */
char           d_name[256]; /* File name string */ with the NULL terminating character
};
Copy the code

closedir

  1. The header file:
    1. #include <sys/types.h>
    2. #include <dirent.h>
  2. Prototype: int Closedir (DIR *dirp); `
  3. Function: Turns off a directory stream pointer
  4. Parameter: target directory stream pointer
  5. The return value:
    1. Returns 0 on success;
    2. Returns -1 on failure;

Code:

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>

int main(int argc, const char *argv[])
{
    // Open a directory
    DIR *mydir =  opendir(".");
    if(NULL == mydir)
    {
        perror("opendir");
        return - 1;
    }
    // Start reading the file
    struct dirent * mydirent; Struct dirent * to receive read return value
    while(NULL! = (mydirent = readdir(mydir))) {printf("File name %s\n",mydirent->d_name);

    }
    closedir(mydir);
    return 0;
}  
Copy the code
linux@ubuntu:~/demo/test/IO/test$./a.out The file name is. The file name is test.c. The file name is a.out. The file name is core. The file name is 1.txtCopy the code

📝 practice:

Ls-l can be implemented with or without parameters