File IO operation

Posted by nasser on Mon, 21 Feb 2022 12:53:26 +0100

head.h

#ifndef _HEAD_H_
#define _HEAD_H_

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#endif

01_open.c

         1.open
        int open(const char *pathname, int flags); // Open an existing file
        int open(const char *pathname, int flags,int mode);//O_CREAT + permissions
Function:
Get a file descriptor
Parameters:
pathname: file name
            flags:
Required item: they are mutually exclusive, so there can only be one
                O_RDONLY    "r"
                O_WRONLY    
                O_RDWR      "r+"
Optional:
            O_ Create / / create a file. If the file exists, only open it. / / this flag exists, you need to specify the parameter mode
        
            O_TRUNC # file contents empty
            O_APPEND mode
            
/ / later
            O_NOCTTY # is not a terminal device
            O_ASYNC # asynchronous io, when io is uncertain,
            O_NONBLOCK non blocking

Return value:
Successfully returned file descriptor (least recently unused)
Failure Return - 1
                        
            open("1.txt",O_WRONLY|O_CREAT,0666);

======================================================================

            "r"     O_RDONLY
            "r+"    O_RDWR
            "w"        O_WRONLY | O_CREAT | O_TRUNC,0064
            "w+"    O_RDWR | O_CREAT | O_TRUNC,0064
            "a"     O_WRONLY | O_APPEN | O_CREAT,0064
            "a+"    O_RDWR | O_APPEN | O_CREAT,0664

         2.close
        int close(int fd);
Function:
Close file descriptor

#include "head.h"

int main(void)
{
	int fd = open("1.txt",O_RDWR | O_CREAT | O_TRUNC,0664);
	if(-1 == fd)
	{
		printf("fail to open.\n");
		return -1;
	}
	printf("fd = %d\n",fd);

	close(fd);
	
	return 0;
}

02_write.c

         3.write
        char buf[1024];
        ssize_t write(int fd,  const  void *buf, size_t count);
Function:
Write a string of data to a file through a file descriptor
Parameters:
fd: file descriptor
buf: the first address of the string to be written to the file
count: the number of characters to write
Return value:
Successfully returned the number of actual writes
Failure Return - 1

#include "head.h"

int main(void)
{
	int fd = open("1.txt",O_RDWR | O_CREAT | O_TRUNC,0664);
	if(-1 == fd)
	{
		printf("fail to open.\n");
		return -1;
	}

	char buff[] = {"hello world"};
	ssize_t ret = write(fd,buff,strlen(buff));
	printf("ret = %ld\n",ret);

	close(fd);
	
	return 0;
}

03_read.c

         4.read
        ssize_t read(int fd, void *buf, size_t count);
Function:
Read the data in the file through the file descriptor
Parameters:
fd: file descriptor
buf: the first address of the storage data space
count: the number of data to be read
Return value:
Successfully return the number of data read
Failure Return - 1
Return 0 when reading the end of the file

#include "head.h"

int main(void)
{
	int fd = open("1.txt",O_RDONLY);
	if(-1 == fd)
	{
		printf("fail to open.\n");
		return -1;
	}

	char buff[1024] = {"lllllllllllllllllllllllllll"};
	memset(buff,0,sizeof(buff));//Clear the specified space into the characters you want
	ssize_t ret = read(fd,buff,sizeof(buff));
	printf("ret = %ld\n",ret);
	printf("%s\n",buff);

	close(fd);
	
	return 0;
}

04_lseek.c

         5.lseek  
        off_t lseek(int fd, off_t offset, int whence);
Function:
Relocating the offset of a file descriptor (file locator)
Parameters:
fd: file descriptor
Offset: offset
Positive: offset backward
Negative: forward offset
Zero: no offset
            whence:
                SEEK_SET
                SEEK_CUR
                SEEK_END
Positive cavity
Return value:
Successfully return the value of the current offset (off_t# long int)
Failure Return - 1
            
            off_t len =lseek(fd,0,SEEK_END); // Gets the size of the file

#include"head.h"

int main(int argc, const char *argv[])
{
	int fd = open("1.txt",O_RDWR | O_CREAT,0664);
	if(-1 == fd)
	{
		printf("fail to open.\n");
		return -1;
	}
    off_t offset = lseek(fd,3,SEEK_SET);
	printf("offset = %ld\n",offset);
	write(fd,"A",1);

	offset = lseek(fd,4,SEEK_CUR);
	printf("offset = %ld\n",offset);
	write(fd,"B",1);

	offset = lseek(fd,-2,SEEK_END);
	printf("offset = %ld\n",offset);
	write(fd,"C",1);

	offset = lseek(fd,0,SEEK_END);
	printf("len = %ld\n",offset);

	close(fd);
	
	return 0;
}

05_buffer.c

06_fileno.c

 1.fileno      FILE* fp -> int fd
int fileno(FILE *stream);
Function:
Get a file descriptor in the file stream pointer
Parameters:
Stream: file stream pointer
Return value:
File descriptor returned successfully
Failure Return - 1

#include "head.h"

int main(int argc, const char *argv[])
{
	FILE *fp = fopen("1.txt","r+");
	int fd = fileno(fp);

	write(fd,"hello world",11);
	fclose(fp);
	return 0;
}

07_fdopen.c

 2.fdopen    int fd -> FILE *fp
 FILE *fdopen(int fd, const char *mode);
Function:
Converts a file descriptor to a file stream pointer
Parameters:
fd: open file descriptor
    mode:
        "r"
        "r+"
        "w"
        "w+"
        "a"
        "a+"
Return value:
File stream pointer returned successfully
Failure returns NULL

#include "head.h"

int main(int argc, const char *argv[])
{
	int fd = open("1.txt",O_RDONLY);
	FILE * fp = fdopen(fd,"r");
	char buff[1024] = {0};
	fgets(buff,sizeof(buff),fp);
	printf("%s",buff);
	close(fd);
	
	return 0;
}

08_time.c

         1.time
          time_t time(time_t *t);
Function:
Get the number of seconds from January 1, 1970 to now
Parameters:
t: the first address of the storage space for seconds
Return value:
Successfully returned the number of seconds from January 1, 1970 to the present (time_t# long)
Failure Return - 1
       
          time_ Tseconds from January 1, 1970 to now
Calendar time

        2.ctime
          char *ctime(const time_t *timep);
Function:
Convert seconds to string time
Parameters:
Time: the number of seconds from January 1, 1970 to now
Return value:
First address of time string returned successfully
Failure returns NULL

         3.localtime
           struct tm *localtime(const time_t *timep);
Function:
Convert seconds to time structure
Parameters:
Time: the first address of the space where the seconds are stored
Return value:
The first address of the space containing the time structure is returned successfully
Failure returns NULL
        
           struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };

#include "head.h"


int main(int argc, const char *argv[])
{
	FILE *fp = fopen("1.txt","w+");
	time_t sec = 0;
	time(&sec);
//	printf("sec = %ld\n",sec);

	char *pt = ctime(&sec);
//	printf("pt = %s",pt);

	struct tm * ptime = localtime(&sec);
	printf("%d-%d-%d %d:%d:%d\n",ptime->tm_year+1900,ptime->tm_mon+1,ptime->tm_mday,ptime->tm_hour,ptime->tm_min,ptime->tm_sec);
	
	char buff[1024] = {0};
	fgets(buff,sizeof(buff),stdin);
	fputs(buff,fp);
	return 0;
}

09_log.c  

#include "head.h"

int main(int argc, const char *argv[])
{
	FILE *fp = fopen("log.txt","a");
	if(NULL == fp)
	{
		printf("fail to fopen.\n");
		return -1;
	}

	while(1)
	{
		char buff[1024] = {0};
		fgets(buff,sizeof(buff),stdin);
		buff[strlen(buff) - 1] = '\0';

		time_t sec;
		time(&sec);
		struct tm * pt = localtime(&sec);
		fprintf(fp,"%s %d-%d-%d %d:%d:%d\n",buff,pt->tm_year+1900,pt->tm_mon+1,pt->tm_mday,pt->tm_hour,pt->tm_min,pt->tm_sec);
		fflush(fp);
		if(strcmp(buff,"quit") == 0)
		{
			break;
		}
	}
	fclose(fp);
	return 0;
}

Topics: C C++