“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
- Standard input: stdin —- keyboard file
- Standard output: stdout —- terminal file
- 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:
-
Buffer full flush buffer
-
The program finishes flushing the buffer
-
The program flushes the buffer manually
fflush
- Prototype:
int fflush(FILE *stream);
- Function: Refresh buffer
- Parameter: target file stream pointer
- The return value:
- Success: 0
- 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:
-
Flush the buffer if the buffer is full
-
The buffer is flushed when it encounters \n
-
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
-
Fflush flushes the buffer
-
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
-
#include
-
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
-
Function: Get the number of seconds from the current computer time to 1970-01-00-00-00
-
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
-
The return value:
- The number of seconds from 1970-01-00-00-00 to the present was successfully returned
- 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
- Prototype:
char *ctime(const time_t *timep);
- Function: according to the fixed format will now convert the time out
- Argument: address of a variable of type time_t
- The return value:
- Success returns the first address of the wrapped string
- Returns NULL on failure
- 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
- Prototype:
struct tm *localtime(const time_t *timep);
- Function: The timep will be converted to the present time, the data stored in the structure
- Parameter: address of the seconds variable
- The return value:
- Success: an encapsulated TM structure is returned
- 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
- The header file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
- Prototype:
int stat(const char *pathname, struct stat *statbuf);
- Run the following command to obtain the status of a file
- Parameters:
- Pathname: indicates the path and name of the target file
- Statbuf: structure address for storing file attribute information
- The return value:
- Returns 0 on success
- 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
- The header file:
#include <sys/types.h>
#include <pwd.h>
- Prototype:
struct passwd *getpwuid(uid_t uid);
- Function: Query user information by ID number and encapsulate structure
- Parameter: User ID number
- The return value:
- Returns the encapsulated structure passwd successfully
- 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
- The header file:
- #include <sys/types.h>
- #include <grp.h>
- Struct group *getgrgid(gid_gid);
- Parameter: Group ID
- The return value:
- Returns the encapsulated structure address successfully
- 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
- The header file:
#include <sys/types.h>
#include <dirent.h>
- Prototype:
DIR *opendir(const char *name);
- DIR: directory flow pointer —– Flag to open a directory for future use
- Parameter: name: path of the directory to be opened
- Return value:
- The directory flow pointer was returned successfully
- Return NULL on failure
readdir
-
Header file: #include
-
Struct dirent *readdir(DIR *dirp);
-
Function: Read directory files
-
Parameter: target directory stream pointer
-
The return value:
- Success returns the address of an encapsulated directory information structure
- Return NULL on failure
- Return NULL after reading to end of file
-
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
- The header file:
#include <sys/types.h>
#include <dirent.h>
- Prototype: int Closedir (DIR *dirp); `
- Function: Turns off a directory stream pointer
- Parameter: target directory stream pointer
- The return value:
- Returns 0 on success;
- 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