Linux --- file operation

File reading & writing in C language

#include <stdio.h>

int main()
{
  FILE* fp = fopen("log.txt","r");
  if(fp == NULL)
  {
    perror("fopen");
    return 1;
  }
  int ct = 5;
  char buf[64];
  while(ct){
  
    fgets(buf,sizeof(buf),fp);
    printf(buf);
    ct--;
  }
  /*
  int ct = 5;
  while(ct)
  {
    fputs("hello world \n",fp);
    ct--;
  }
  */
  fclose(fp);
  return 0;
}

stdin

Standard input

FILE* fp = fopen("log.txt","r");
  if(fp == NULL)
  {
    perror("fopen");
    return 1;
  }
  int ct = 5;
  char buf[64];
  while(ct){
  
    fgets(buf,sizeof(buf),stdin);
    printf(buf);
    ct--;
  }

stdout

standard output

int ct = 5;
  while(ct)
  {
    fputs("hello world \n",stdout);
    ct--;
  }

stderr

Standard error

int ct = 5;
  while(ct)
  {
    fputs("hello world \n",stderr);
    ct--;
  }

a – append write

#include <stdio.h>

int main()
{
  FILE* fp = fopen("log.txt","a");//append
  if(fp == NULL)
  {
    perror("fopen");
    return 1;
  }
  int ct = 5;
  while(ct)
  {
    fputs("hello L \n",fp);
    ct--;
  }
  
  fclose(fp);
  return 0;
}

Write -- overwrite write

#include <stdio.h>

int main()
{
  FILE* fp = fopen("log.txt","w");
  if(fp == NULL)
  {
    perror("fopen");
    return 1;
  }
  int ct = 5;
  while(ct)
  {
    fputs("welcome!\n",fp);
    ct--;
  }
  
  fclose(fp);
  return 0;
}

I/O in the system

Interface

  • O_RDONLY read only open
  • O_WRONLY write only open
  • O_RDWR read / write on
  • O_CREAT creates if the file does not exist
  • O_APPEND append write
  • Open successfully, return value greater than 0
  • Open failed, return 1

File descriptor

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

int main()
{
  int fd = open("log.txt",O_WRONLY,0666);
  printf("fd: %d\n",fd);

  return 0;
}

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

int main()
{
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",fd);

  return 0;
}


Find flag bit


open

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

int main()
{
  int f1 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f1);
  int f2 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f2);
  int f3 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f3);
  int f4 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f4);
  int f5 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f5);

  return 0;
}

write&close

const char* msg = "welcome L\n";
  write(1,msg,strlen(msg));

char buff[32];
  read(0,buff,32);
  printf("%s\n",buff);

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
  int f1 = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(f1 < 0){
    
    printf("open error!\n");
  }
  printf("fd: %d\n",f1);
  
  int ct = 5;
  const char* msg = "hello world!\n";
  while(ct)
  {
    write(f1,msg,strlen(msg));//strlen does not require + 1
    ct--;
  }

  close(f1);
  return 0;
}

read

#include <string.h>
int main()
{
  int f1 = open("log.txt",O_RDONLY);
  if(f1 < 0){
    
    printf("open error!\n");
  }
  printf("fd: %d\n",f1);
  
  char c;
  while(1)
  {
    ssize_t s = read(f1,&c,1);
    if(s <= 0)
    {
      break;
    }
    write(1,&c,1);//fwrite(,,,stdout);
  }
  close(f1);

  return 0;
}

File identifier assignment rule

Allocate from the smallest but unused


Turn off the display (1)

 close(1);
  int f2 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f2);
  int f3 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f3);
  int f4 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f4);
  int f5 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f5);

  return 0;


Off 0

 close(0);
  int f2 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f2);
  int f3 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f3);
  int f4 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f4);
  int f5 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f5);

  return 0;

 close(0);
 close(2);
  int f2 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f2);
  int f3 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f3);
  int f4 = open("log.txt",O_WRONLY|O_CREAT,0666);
   printf("fd: %d\n",f4);
  int f5 = open("log.txt",O_WRONLY|O_CREAT,0666);
  printf("fd: %d\n",f5);

  return 0;

int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0){
    return 1;
  }
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);

  close(fd);

close(1);
int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0){
    return 1;
  }
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);
  write(fd,"hello\n",6);

  close(fd);

redirect

Output redirection

close(1);
int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0){
    return 1;
  }
  write(1,"hello\n",6);
  write(1,"hello\n",6);
  write(1,"hello\n",6);
  write(1,"hello\n",6);
  write(1,"hello\n",6);

  close(fd);

close(1);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);            
   if(fd < 0){                                                
      return 1;                                                
    }                      

   printf("hello you:%d\n",123);
   printf("hello you:%c\n",'v');
   printf("hello you:%f\n",3.335);
   fflush(stdout);

 close(1);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);            
   if(fd < 0){                                                
      return 1;                                                
    }                      

   printf("hello",stdout);
   printf("hello",stdout);
   printf("hello",stdout);

  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);            
   if(fd < 0){                                                
      return 1;                                                
    }                      

   printf("hello",stdout);
   printf("hello",stdout);
   printf("hello",stdout);


The essence of redirection is to modify the content pointed to by the struct file corresponding to the subscript of the file descriptor*
struct FILE is a structure that must contain a member called fd

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  umask(0);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE*
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fputs("hello fputs %d %c %c\n",stdout);
  close(fd);
  return 0;

}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  close(1);//fd = 1
  umask(0);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE *, and only stdout(FILE *) interfaces
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fputs("hello fputs %d %c %c\n",stdout);
  close(fd);
  return 0;

}

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  close(1);//fd = 1
  umask(0);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE *, and only stdout(FILE *) interfaces
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fflush(stdout);//Let the information be displayed in the file
  fputs("hello fputs %d %c %c\n",stdout);
  close(fd);
  return 0;

}



Standard input

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  umask(0);
  int fd = open("log.txt",O_RDONLY,0666);
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE *, and only stdout(FILE *) interfaces
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fputs("hello fputs %d %c %c\n",stdout);
 fflush(stdout);//Let the information be displayed in the file

 char buff[50];
 fgets(buff,50,stdin);
 printf("%s\n",buff);
 close(fd);
  return 0;

}

Output redirection

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
 close(0);//stdin
  umask(0);
  int fd = open("log.txt",O_RDONLY,0666);
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE *, and only stdout(FILE *) interfaces
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fputs("hello fputs %d %c %c\n",stdout);
 fflush(stdout);//Let the information be displayed in the file

 char buff[50];
 fgets(buff,50,stdin);
 printf("%s\n",buff);
 close(fd);
  return 0;

}

Append redirection

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
  close(1);//fd = 1

  umask(0);
  int fd = open("log.txt",O_WRONLY|O_APPEND);//a
  if(fd < 0)
  {
    perror("open");
    return 1;
  }
  //All belong to C,FILE *, and only stdout(FILE *) interfaces
  printf("hello printf!\n");//stdout printf encapsulates stdout internally
  fprintf(stdout,"hello fprintf!\n");
  fputs("hello fputs %d %c %c\n",stdout);
 fflush(stdout);//Let the information be displayed in the file

 return 0;

}


All contents displayed on the display / read from the keyboard are characters. Therefore, the keyboard and display are generally called "character devices"

scanf/printf format input / output requires converting numbers into characters according to ASCII table

See the difference between FD 1 & 2

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
  
  printf("hello printf!\n");//stdout
  perror("perror");//stderr
  fprintf(stdout,"stdout : hello fprintf\n");
  fprintf(stderr,"stderr : hello fprintf\n");
  return 0;
}



Redirection 1 does not print on the display, but does not affect 2, so the content with fd=2 is displayed on the display

Batch replacement

NOMAL mode

  • 1. Press ESC
  • :% s / replaced / replaced / g

Using dup2 system call

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
 
  umask(0);
  int fd = open("log.txt",O_WRONLY|O_CREAT,0666);
  if(fd < 0){
    perror("open");
    return 1;
  }
  close(1);//Open before redirecting
  dup2(fd,1);
  printf("hello printf\n");
  fprintf(stdout,"hello fprintf\n");
  fputs("hello fputs:%d %c %f\n",stdout);
  fflush(stdout);
  close(fd);
  return 0;
}

Add redirection in myshell

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>
#define len 1024
#define num 32
int main()
{
  int type = 0;//0 > 1 >> 2 <
  char cmd[len];
  char* myarg[num];
  while(1)
  {
    printf("[L@my_centos_mc dir]$");
    fgets(cmd,len,stdin);
    cmd[strlen(cmd)-1] = '\0';
    //printf("%s",cmd);
    //Parse string
    //char* start  = cmd + strlen(cmd) - 1;
    char* start = cmd;
    while(*start != '\0')
    {
      if(*start == '>')
      {
        type = 0;
        *start = '\0';
        start ++;
        if(*start == '>')
        {
          type = 1;
          start++;
        }
        break;
      }
      if(*start == '<')
      {
        type = 2;
        *start = '\0';
        start++;
        break;
      }
      //start --;
      start++;
    }
    if(*start != '\0')
    {
      while(isspace(*start)){
        start++;
      }
      //printf("%s\n",start);
    }
    else{
      start = NULL;
    }
    myarg[0] = strtok(cmd," ");
    int i = 1;
    while(myarg[i] = strtok(NULL," "))
    {
      i++;
    }
    pid_t id = fork();
    if(id == 0)
    {
      //child
     if(start != NULL)
     {
       if(type == 0){
       
         int fd = open(start,O_CREAT|O_WRONLY,0644);
       
         if(fd < 0)
        {
          perror("open");
         exit(2);
        }
        dup2(fd,1);
       }
     }
     else if(type == 1)
     {
         int fd = open(start,O_APPEND,0644);
         if(fd < 0){
        
           perror("open");
           exit(2);
          }
         dup2(fd,1);
     }
     else if(type == 2)
     {
       int fd = open(start,O_RDONLY,0644);
       dup2(fd,0);
     }
     else{

     }
      execvp(myarg[0],myarg);
      exit(10);
    }
    int status = 0;
    pid_t ret = waitpid(id,&status,0);
    if(ret > 0)
    {
      printf("exit code: %d\n",WEXITSTATUS(status));
    }
  }
  /*
  char name[32];
  while(1)
  {
    gethostname(name,sizeof(name)-1);
    printf("%s\n",name);
  }*/
  return 0;
}

FILE

  • IO related function interfaces correspond to system call functions, and library functions encapsulate system calls, so in essence, files are accessed through fd
  • Inside the FILE structure in the C library, fd is encapsulated

Explain that everything is a file under Linux

buffer

#include <stdio.h>
#include <unistd.h>
int main()
{
  /*
  printf("hello world!\n");//Execute Hello world first \ n
  sleep(3);
  */
  printf("hello world!");//It is saved to the buffer for 3 seconds and then refreshed
  sleep(3);
  //fflush(stdout);// Will be refreshed immediately
  return 0;
}

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
 
  //C language function
  printf("hello printf\n");
  fprintf(stdout,"hello fprintf\n");
  //system
  const char* msg = "hello write\n";
  write(1,msg,strlen(msg));
  return 0;
}

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
  //C language function
  printf("hello printf\n");
  fprintf(stdout,"hello fprintf\n");
  //system
  const char* msg = "hello write\n";
  write(1,msg,strlen(msg));
  
  fork();
  return 0;
}



file system

  • pattern
  • Number of disk links
  • File owner
  • group
  • size
  • Last modified date
  • file name

disk

View disk


inode

View inode number: ls -l -i




Hard and soft links

#include <stdio.h>

int main()
{
  printf("hello new !\n");
  return 0;
}

Establish soft link

ln -s file  file-s

Establish hard link

ln  file  file-h





  • Access: last accessed time
  • Modify: last modified time
  • Change: change of file attributes

Dynamic and static libraries

Linux
. so: dynamic library
. a: static library
Windows
. dll: dynamic library
. lib: static library

Change dynamic library into static library

gcc -o file file.c -static

  • Static library (. a): the program links the code of the library to the executable file when compiling the link. The static library will no longer be needed when the program runs
  • Dynamic library (. so): the code of the dynamic library is linked only when the program is running. Multiple programs share the code of the library
  • The executable file linked to a dynamic library only contains a table of the function entry address it uses, not the whole machine code of the target file where the external function is located
  • Before the executable starts running, the machine code of the external function is copied from the dynamic library on disk to memory by the operating system. This process is called dynamic link
  • Dynamic libraries can be shared in multiple programs, so dynamic links make executable files smaller and save disk space. The operating system adopts the virtual memory mechanism, which allows a dynamic library in physical memory to be shared by all processes using the library, saving memory and disk space

Static library
Disadvantages: it takes up space (memory + disk). When multiple static library programs are loaded, there must be a lot of duplicate code in memory
Advantages: it has nothing to do with the library and does not need the library
Dynamic library:
Advantages: save space (memory space), and library files are shared through address space
Disadvantages: it must rely on the library. Without the library, it cannot run

Generate static library

  • Generate static library: ar -rc libmymath.a file.o test.oar is a gnu archive tool, rc(replace and create)
cat Makefile 
mylib=libcal.a
CC=gcc
$(mylib):add.o sub.o
		ar -rc $(mylib) $^

%.o:%.c
		$(CC) -c $<
.PHONY:clean
clean:
		rm -f $(mylib) *.o
.PHONY:output
output:
		mkdir -p mathlib/lib 
		mkdir -p mathlib/include 
		cp *.h mathlib/include
		cp *.a mathlib/lib 


  • View the directory list in the static library: ar -tv libmymath.a test.o file.o t: list the file v:verbose details of the static library

cat test.c
#include <stdio.h>
#include <add.h>
int main()
{
  int x = 10;
  int y = 20;
  int z = my_add(x,y);
  printf("%d\n",z);
  return 0;
}

  • -I: where is the header file
  • -50: Where are the library files
  • -l: Which library is linked

Process of installing Libraries

Copy the library to the system path

sudo cp mathlib/include/* /usr/include/

Generate dynamic library

  • Shared: indicates the format of generating shared library
  • FPIC: generate position independent code
  • Library name rule: libxxx.so

Using dynamic libraries

  • l: Link the dynamic library as long as the library name (remove lib and version number)
  • 50: The path where the linked library is located

Run dynamic library

  • Copy the. so file to the system shared library path, which generally refers to / usr/lib
  • Change LD_LIBRARY_PATH













  • Ldconfig configuration / etc/ld.so.conf.d/,ldconfig update

Using external libraries

  • -lm means to link libm.so or libm.a library file

Keywords: Linux

Added by Akito on Sun, 24 Oct 2021 03:18:02 +0300