C summary part 6 file management

Keywords: Programming ascii Windows encoding Linux

10_ file

  • Text files: Based on character encoding, such as ASCII, UNICODE
  • Binary

file open

FILE *fopen(filename, mode);

// The system itself defines a structure called FILE
// Mode indicates the mode of opening the file

/*
mode The value of
    r rb    Open as read-only
    w wb    Open as write
    a ab    Open as append, add content at the end
    r+ rb+  Open in readable and writable mode without creating a new file
    w+ wb+  Open in readable and writable mode, and empty the file if it exists
    a+ ab+  Open file as added

Tips: b It refers to binary mode, which is special for windows;
*/
FILE *fp = fopen("xx.txt","r");
if(fp == NULL)
{
    printf("File open failed"); 
    return;
}
printf("Open failure");

fclose(fp); //Close file

/*
There are several cases of file open failure
1,File not found, wrong path
2,No read-write permission
3,The number of files opened by the program exceeds the upper limit (generally 65535 files);
*/

fputc('A',fp); // Overwrite
char ch = fgetc(fp); // Read a character

while(ch == fgetc(fp) != EOF)

/*
The default EOF at the end of the file is - 1;
With fgetc once, a character will be read from the file, and the cursor in the file will step forward;
*/
char ch;
while((ch = fgetc(fp)) != EOF)
{
    printf("%c\n",ch);
}
// The ASCII value of EOF is - 1, and the values of characters in ASCII are all positive, so it can be used as the end flag;

char ch = 'a';
FILE *fp = fopen("./b.txt","a");
fputc(ch,fp);
ch = 'b';
fputc(ch, fp);  // At this point, the string ab is in the b.txt file

// Implement a vi editor
scanf("%s",fileName);
getchar(); // At the end of scanf, use \ n, getchar is used to receive \ n, to avoid problems caused by multiple scanf;

// Update the buffer, for example, when the terminal program is input, the original input content will be cached with fflush;
fflush(p); 

// Target: use the command myvi. / a.txt to edit a.txt
//For example, implement cat, that is, view the text file;
//Cat. / a.txt will now display all contents of the file
// Example, four operations
sprint(buf, "%d%c%d=\n",a,b,c);
// For example, type 2*3=\n and it will be put into buf
//Encryption and decryption of files
/*
Simple encryption
    1. Read the file, add 1 to the ASCII code of all characters,
    2. Write the contents of the post reading processing to another file;

Decrypt
    1. Read the file and subtract 1 from the ASCII code of polite characters,
    2. Write the processed content to another file

Tips: md5 is a common encryption method;
*/

Read and write files by characters → read one character at a time

  • Read fgetc()
  • Write fputc()
  • Whether to the end of the file feof()

Read and write file by line → also called block read, and the read length can be specified

  • Read fgets()
  • Write fputs()
char buf[1024];
fgets(buf, 5,fp); 
/*
fp Is the fileStream obtained through fopen
5 Is the number of reads. In the actual reading, if you pass in 5, you will read 4 characters. The remaining 1 character is \ 0 as the end of the character;
The number of reads can exceed the size of fp
*/
// The buf defined directly by char is stored in the stack with limited space
char buf[1024]; 

// The space of malloc application is in the heap space, which is large
char *uf = malloc(sizeof(char *) * 1024);
while(feof(fp) == 0){}
/*
feof()Determine whether the file has reached the end
    =0  Description not to end
    ≠0  The description is at the end

Tips: EOF Is to determine the end of the character, while feof() is to determine whether the file stream is to the end
*/
/*
Format and read out of string: extract variable values from buf according to the format of "% d%c%d=\n" and assign them to abc
*/
sscanf(buf, "%d%c%d=\n",&a,&b,&c);


/*
Format write of file: string a b c value in the format of "% d%c%d=%.2f\n" and store it in buf
*/
fprintf(buf, "%d%c%d=%.2f\n",a,b,c,value);

// The above sentence is equivalent to
memset(buf,0,20);
sprintf(buf,"%d%c%d=%.2f\n",a,b,c,value);
fputs(buf,fp2);

/*
Format read of file
*/
fscanf(fp1, "%d+%d=%d\n",&a, &b, &c);
  • scanf() - printf()
  • sscanf() - sprintf()
  • fscanf() - fprintf()
printf("===%5d===",1);
/*
%5d     ____1,First four spaces
%-5d    1____,Next four spaces
%.5d    00001
%-.5d   00001

%ld     Print long type
*/
//For example, use fscanf(), fprintf() to implement four operation writes

//For example, use structure to complete four operations reading and writing
// Example, 10000 data sorting
/*
Tips: The first thought is bubble sorting, but the number of execution times of bubble is 10000 + 9999 + 9998 +
100000 Data sorting, bubble sorting takes 35s
*/

// How to record the running time?
unsigned int start_time = time(NULL);
...Intermediate code operation...
int end_time = time(NULL);
end_time - start_time → That is, program running time

/*
Tips: For regular numbers, you can trade space for time,
For example, 100000 numbers of 1-1000 can be defined as an arr[1000], and the number of times a number I occurs as the value of arr[i]
In this case, the sorting time can be shortened to 1s
*/

-----------------------

Read and write by block

fread(*ptr , size_t , nmemb , stream);

  • Address to be read and written by ptr
  • Size? The size of the block
  • Number of nmemb blocks
  • Stream file stream

fwrite( )

Total read / write size = block size * number of blocks

// Move the cursor for reading and writing
FILE *fp = fopen("../../d.txt", "r");
fseek(fp, 6 , SEEK_SET);
fseek(fp, -5 , SEEK_END);

// The cursor moves forward n positions, even if the file cursor has reached the beginning, there will still be a relative distance

ftell(fp); Return to the read / write location of the current file

rewind(fp) Return the cursor to the beginning

Tips: windows text file ends with \ r\n,
linux and unix text files end with \ n,
However, when reading, windows will automatically convert \ r\n to \ r\n, which is not available if viewed as binary

-----------------------

Delete and rename files

remove(pathname)
rename(oldpath, newpath)

0 on success
Return - 1 on failure

-----------------------

file buffer

int fflush(FILE *stream)
Write buffer data to file now

Cache → the file content of the current operation
Update to file → write contents of current operation to disk

Program compilation

  • Preprocessing
  • Compile
  • assembly
  • Connect

-----------------------

Posted by hillbilly928 on Sun, 01 Mar 2020 00:21:59 -0800