当前位置:网站首页>C language file operation for conquering C language
C language file operation for conquering C language
2022-07-01 00:33:00 【LYC_ four hundred and sixty-two million eight hundred and fifty】
Catalog
3. Opening and closing of files
3.2 Opening and closing of files
4. Sequential reading and writing of files
Add : Realization of address book
4.1 Compare a set of functions :
5. Random reading and writing of documents
7. Determination of the end of file reading
Example : Write code to test.txt A copy of the document , Generate test2.txt
Key points of this chapter
1. Why use files
2. What is a document
2.1 Program files
Include source files ( The suffix is .c), Target file (windows Environment suffix is .obj), Executable program (windows Environment suffix is .exe).
2.2 Data files
The content of the file is not necessarily a program , It's the data that the program reads and writes when it runs , For example, the file from which the program needs to read data , Or output content file .
2.3 file name
3. Opening and closing of files
3.1 The file pointer
struct _iobuf {char *_ptr;int _cnt;char *_base;int _flag;int _file;int _charbuf;int _bufsiz;char *_tmpfname;};typedef struct _iobuf FILE;
FILE* pf;// File pointer variable


3.2 Opening and closing of files
// Open fileFILE * fopen ( const char * filename, const char * mode );// Close fileint fclose ( FILE * stream );
Open it as follows :
| How files are used | meaning | If the specified file does not exist |
“r”( read-only ) | To enter data , Open an existing text file | error |
“w”( Just write ) | To output data , Open a text file | Create a new file |
| “a”( Additional ) | Add data to the end of the text file | Create a new file |
| “rb”( read-only ) To enter data , | Open a binary file | error |
wb”( Just write ) | To output data , Open a binary file | Create a new file |
| “ab”( Additional ) | Add data to the end of a binary file | error |
| “r+”( Reading and writing ) | For reading and writing , Open a text file | error |
“w+”( Reading and writing ) | For reading and writing , Create a new file | Create a new file |
| “a+”( Reading and writing ) | Open a file , Read and write at the end of the file | Create a new file |
| “rb+”( Reading and writing ) | Open a binary file for reading and writing | error |
“wb+”( Reading and writing ) | For reading and writing , Create a new binary file | Create a new file |
| “ab+”( Reading and writing ) | Open a binary file , Read and write at the end of the file | Create a new file |
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("code11.c", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Writing documents
// Close file
fclose(pf);
pf = NULL;
return 0;
}
- With w The form opens , If not, a new file will be created automatically
- Opening it again will overwrite the previous content
4. Sequential reading and writing of files
function | Function name | Apply to |
| Character input function | fgetc | All input streams |
| Character output function | fputc | All output streams |
Text line input function | fgets | All input streams |
| Text line output function | fputs | All output streams |
| Format input function | fscanf | All input streams |
Format output function | fprintf | All output streams |
| Binary input | fread | file |
| Binary output | fwrite | file |

Code 1 :fputc

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("C:\\Users\\46285\\source\\repos\\code\code11.c", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Writing documents
fputc('b', pf);
fputc('i', pf);
fputc('t', pf);
// Close file
fclose(pf);
pf = NULL;
return 0;
}- Here I open the file by relative path
- Pay attention to joining \ Transference


Add : Flow is a highly abstract concept ,C Language program , Just run , It is turned on by default 3 A flow
- stdin - Standard input stream - keyboard
- stdout - Standard output stream - The screen
- stderr - Standard error flow - The screen

Code 2 :fgetc

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("code11.c", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Reading documents
int ret = fgetc(pf);
printf("%c\n", ret);
ret = fgetc(pf);
printf("%c\n", ret);
ret = fgetc(pf);
printf("%c\n", ret);
// Close file
fclose(pf);
pf = NULL;
return 0;
}
Code three :fputs

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("code11.c", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Writing documents - Write in line
fputs("abcdef\n", pf);
fputs("qwertyuiop\n", pf);
// Close file
fclose(pf);
pf = NULL;
return 0;
}
Code four :fgets

- there num It includes \0
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
char arr[10] = "xxxxxx";
FILE* pf = fopen("code11.c", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Reading documents
fgets(arr, 4, pf);
printf("%s\n", arr);
// Close file
fclose(pf);
pf = NULL;
return 0;
}Code five :fscanf and fprintf


#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = { "abcdef", 10, 5.5f };
// Write the formatted data to a file
FILE* pf = fopen("code11.c", "w");
if (NULL == pf)
{
perror("fopen");
return 1;
}
// Reading documents
fscanf(pf, "%s %d %f", s.arr, &(s.num), &(s.sc));
// Print
fprintf(stdout, "%s %d %f\n", s.arr, s.num, s.sc);
// Close file
fclose(pf);
pf = NULL;
return 0;
}

Code six :fwrite

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = { "abcde", 10, 5.5f };
// Write in binary form
FILE*pf = fopen("code11.c", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Writing documents
fwrite(&s, sizeof(struct S), 1, pf);
// Close file
fclose(pf);
pf = NULL;
return 0;
}
- Binary character or character , Although we can't understand the latter, we can use fread
Code seven :fread

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = {0};
// Read in binary form
FILE*pf = fopen("code11.c", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Reading documents
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %f\n", s.arr, s.num, s.sc);
// Close file
fclose(pf);
pf = NULL;
return 0;
}- fread and fwrite Are for binary ,
Add : Realization of address book
Mail list - Dynamic version
- The address book can store 1000 Personal information , Everyone's information : name + Age + Gender + Telephone + Address
- Increase people's information
- Delete the information of the designated person
- Modify the information of the designated person
- Find the information of the designated person
- Sort the information of the address book
- When exiting... Is added , The function of saving address book
- Added the function of retyping to start loading the address book
4.1 Compare a set of functions :
scanf/fscanf/sscanfprintf/fprintf/sprintf

sprintf and sscanf




#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
struct S
{
char arr[10];
int age;
float f;
};
int main()
{
struct S s = { "hello", 20, 5.5f };
struct S tmp = { 0 };
char buf[100] = {0};
//sprintf Put a formatted data , Convert to string
sprintf(buf, "%s %d %f", s.arr, s.age, s.f);
printf("%s\n", buf);
// from buf Restore a structure data in the string
sscanf(buf, "%s %d %f", tmp.arr, &(tmp.age), &(tmp.f));
printf("%s %d %f\n", tmp.arr, tmp.age, tmp.f);
return 0;
} 
- Although the two values are the same , But the form of printing is completely different ,
- These two are like the conversion between formatted data and characters
5. Random reading and writing of documents
All of the following code test.txt It's all this
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read the file
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
// Close file
fclose(pf);
pf = NULL;
return 0;
}
5.1 fseek
Locate the file pointer according to its position and offset .
int fseek ( FILE * stream, long int offset, int origin );
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read the file
int ch = fgetc(pf);
printf("%c\n", ch);
// Adjust file pointer
fseek(pf, -1, SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
// Close file
fclose(pf);
pf = NULL;
return 0;
}


5.2 ftell
Returns the offset of the file pointer from its starting position
long int ftell ( FILE * stream );
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read the file
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
// The offset of the pointer from the starting position
int ret = ftell(pf);
printf("%d\n", ret);
ch = fgetc(pf);
printf("%c\n", ch);
// Close file
fclose(pf);
pf = NULL;
return 0;
}

5.3 rewind
Return the file pointer to the beginning of the file
void rewind ( FILE * stream );
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read the file
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
// Return the file pointer to the starting position
rewind(pf);
// The offset of the pointer from the starting position
int ret = ftell(pf);
printf("%d\n", ret);
ch = fgetc(pf);
printf("%c\n", ch);
// Close file
fclose(pf);
pf = NULL;
return 0;
}
6. Text files and binaries


#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
//0000 0000 0000 0000 0010 0111 0001 0000
//00 00 27 10
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Writing documents
fwrite(&a, sizeof(int), 1, pf);
fclose(pf);
pf = NULL;
return 0;
} 

- If you are interested, you can try this one above
7. Determination of the end of file reading
7.1 Misused feof

Example : Write code to test.txt A copy of the document , Generate test2.txt
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
FILE* pfread = fopen("test.txt", "r");
if (pfread == NULL)
{
return 1;
}
FILE* pfwrite = fopen("test2.txt", "w");
if (pfwrite == NULL)
{
fclose(pfread);
pfread = NULL;
return 1;
}
// File opened successfully
// Read and write files
int ch = 0;
while ((ch = fgetc(pfread)) != EOF)
{
// Writing documents
fputc(ch, pfwrite);
}
if (feof(pfread))
{
printf(" End of file flag encountered , The file ends normally \n");
}
else if(ferror(pfread))
{
printf(" File read failed end \n");
}
// Close file
fclose(pfread);
pfread = NULL;
fclose(pfwrite);
pfwrite = NULL;
return 0;
}


8. File buffer
- As for why there is the concept of buffer , Don't even think about it , To improve efficiency

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <windows.h>
//VS2013 WIN10 Environmental testing
int main()
{
FILE* pf = fopen("test.txt", "w");
fputs("abcdef", pf);// Put the code in the output buffer first
printf(" sleep 10 second - The data has been written , open test.txt file , Found no content in the file \n");
Sleep(10000);
printf(" Refresh buffer \n");
fflush(pf);// When the buffer is flushed , Write the data in the output buffer to a file ( disk )
printf(" Sleep again 10 second - here , Open again test.txt file , There's something in the file \n");
Sleep(10000);
fclose(pf);
// notes :fclose When closing a file , It also flushes the buffer
pf = NULL;
return 0;
}



- fflush In high version VS It can't be used on (vs2019 Use in fflush useless )
边栏推荐
- 6-1 exploit -ftp exploit
- Why should VR panoramic shooting join us? Leverage resources to achieve win-win results
- Gateway service gateway
- Wordpress blog uses volcano engine veimagex for static resource CDN acceleration (free)
- Solutions to errors in installing OpenSSL for CentOS 6.3 x64 PHP 5.2.6 extensions
- SSM integration process (integration configuration, function module development, interface test)
- LVM snapshot: preparation of backup based on LVM snapshot
- 网上开华泰证券的股票账户是否安全呢?
- Basic data structure of redis
- Longest valid bracket
猜你喜欢

Ditto set global paste only text shortcuts

Gateway service gateway

2022-2028 global rotary transmission system industry research and trend analysis report

20220216 misc buuctf backdoor killing (d shield scanning) - clues in the packet (Base64 to image)

Vulnerability discovery - App application vulnerability probe type utilization and repair

From January 11, 2007 to January 11, 2022, I have been in SAP Chengdu Research Institute for 15 years

Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)

Deployment of mini version message queue based on redis6.0

Which is better, server rental or hosting services in the United States?

2022-2028 global single travel industry research and trend analysis report
随机推荐
Development of wireless U-shaped ultrasonic electric toothbrush
Gateway service gateway
2022-2028 global electric yacht industry research and trend analysis report
Bridge emqx cloud data to AWS IOT through the public network
Self examination before school starts
Redis - how to understand publishing and subscribing
Manage edge browser settings (ie mode, homepage binding, etc.) through group policy in the enterprise
$watch will not trigger data change - $watch not firing on data change
Vmware16 installing win11 virtual machine (the most complete step + stepping on the pit)
20220216 misc buuctf another world WinHex, ASCII conversion flag zip file extraction and repair if you give me three days of brightness zip to rar, Morse code waveform conversion mysterious tornado br
CentOS 6.3 x64 PHP 5.2.6 扩展安装OpenSSL出错的解决方法
To tell you the truth, ThreadLocal is really not an advanced thing
Why should VR panoramic shooting join us? Leverage resources to achieve win-win results
The programmer's girlfriend gave me a fatigue driving test
Excuse me, does Flink support synchronizing data to sqlserver
1. crawler's beautifulsoup parsing library & online parsing image verification code
MySQL storage engine
MySQL variables, stored procedures and functions
Using Excel to quickly generate SQL statements
Ditto set global paste only text shortcuts