当前位置:网站首页>C language input / output stream and file operation
C language input / output stream and file operation
2022-07-01 16:43:00 【jie3606】
File operations
What is the file ?
File is a kind of data source , The main function is to save data .
In the operating system , In order to unify the operation of various hardware , Simplify the interface , Different hardware devices are also treated as one file . Operations on these files , Equivalent to the operation of ordinary files on disk . for example :
- The display is often referred to as a standard output file ,printf Is to output data to this file ;
- The keyboard is often referred to as a standard input file ,scanf Reading data from this file .
Files corresponding to common hardware devices
- stdin Standard input file , General keyboard ;scanf()、getchar() By default, functions such as stdin Get input .
- stdout Standard output file , Generally refers to the display ;printf()、putchar() And so on. By default stdout Output data .
- stderr Standard error file , Generally refers to the display ;perror() And so on. By default stderr Output data ( I'll talk about ).
- stdprn Standard print files , Generally refers to the printer .
We're not going to talk about how hardware devices are mapped to files , You just need to remember , stay C In language, hardware devices can be seen as files , Some I / O functions don't require you to specify which file to read or write , The system has set the default file for them , Of course, you can also change , For example, let printf Output data to a file on disk .
The correct flow of operating the file is : Open file --> Read and write files --> Close file . The file should be opened before reading and writing , Shut down after use .
Open a file , It's about getting information about the file , For example, file name 、 File status 、 Current reading and writing position, etc , This information will be saved in a FILE In the structure variable of type .
To close a file is to disconnect from it , Release structure variables , At the same time, it is forbidden to operate the file again .
stay C In language , There are many ways to read and write files , Can be read character by character , You can also read an entire line , You can also read several bytes . The reading and writing positions of files are also very flexible , Can be read from the beginning of the file , It can also be read from the middle .
What is flow ?
file ( Save on disk ) Only when it is loaded into memory can it be processed , The data in memory can only be saved to a file ( disk ) In order not to lose . During this period, we call the transfer of data from file to memory as file flow .
File is a kind of data source , Except for the documents , And databases 、 The Internet 、 Keyboard, etc , Data transferred to memory is saved to C Language variables ( For example, integers 、 character string 、 Array 、 Buffer, etc. ). We put data in data sources and programs ( Memory ) The process of passing between is called Data flow (Data Stream). Corresponding , Data from data source to program ( Memory ) The process is called Input stream (Input Stream), Slave program ( Memory ) The process of getting to the data source is called Output stream (Output Stream).
The difference between a text file and a binary file ?
( stay C In language ) According to the different storage forms of data in files, we put files and binary files .
- text file : Treat the data to be stored as a series of characters , Put the ASCII The code value is stored in the file . Every ASCII The code value takes up one byte (8bit) Each byte represents a character . Therefore, text files are also called character files or ASCII file , It's a character sequence file .
- Binary : Store the corresponding binary form of data in a file , It's a byte sequence file .

C Language file operation
Open and close files
Open file
stay C In language , You must open the file before operating it ; So-called “ Open file ”, Is the process of connecting programs and files .
After opening the file , The program can get the relevant information of the file , For example, size 、 type 、 jurisdiction 、 The creator 、 Update time, etc . In the subsequent process of reading and writing files , The program can also record which location is currently read and written , You can continue to operate on this basis next time .
FILE *fopen( const char *filename, const char *mode );(C99 front )
- filename - The file name associated with the file system
- mode - Open mode
- Return value FILE( Definition and stdio.h A structure type in will be discussed later ) Failed to open the file. Return NULL
File open mode 
call fopen() Function time Read and write permissions must be specified , But you can't specify how to read and write ( here The default is "t").
Read / write permissions and read / write methods can be used in combination , However, the read-write mode must be placed under the read-write permission middle perhaps The tail ( let me put it another way , You cannot put the read-write mode at the beginning of the read-write permission ). for example :
Put the read-write mode at the end of the read-write permission :“rb”、“wt”、“ab”、“r+b”、“w+t”、“a+t”
Put the read-write mode in the middle of the read-write permissions :“rb+”、“wt+”、“ab+”
As a whole , The file is opened by r、w、a、t、b、+ Six characters , What is the meaning of each character :
- r(read): read
- w(write): Write
- a(append): Additional
- t(text): text file
- b(binary): Binary
- +: Read and write
Close file
Once the files are used , Should use the fclose() Function to close the file , To release resources , Avoid data loss .fclose() The usage of is :
int fclose( FILE stream )
- stream - File streams that need to be closed
- Return value Success is 0 , Otherwise EOF .
Close the given file stream . Flush any unwritten buffer data to OS . Discard any unread buffer data . Whether the operation is successful or not , Streams are no longer associated with files . If in fclose Use pointer after returning stream The behavior is undefined .
Example
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main() {
FILE* fp;
char str[N + 1];
if ((fp = fopen("text.txt", "r")) == NULL) {
puts(" File opening failure ");
exit(0);
}
while (fgets(str,N,fp)!=NULL)
{
printf("%s", str);
}
fclose(fp);
return 0;
}
Reading and writing of documents
Read and write files in character form
int fgetc( FILE *stream );
- stream - Read the source of the character
- Return value Characters obtained when successful , On failure: EOF .
int fputc( int ch, FILE *stream );
- ch - The character to be written
- stream - Output stream
- Return value success , Returns the written character . When the failure , return EOF And set up stream Error indicator on ( see ferror() ).
Example
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define N 100
int main() {
FILE* fp;
char ch;
if ((fp = fopen("text.txt", "r+")) == NULL) {
puts(" File opening failure ");
exit(0);
}
while ((ch = fgetc(fp))!=EOF)
{
// Sleep(100);
putchar(ch);
}
while ((ch = getchar()) != '\n') {
fputc(ch, fp);
}
fclose(fp);
return 0;
}
Read and write files as strings
char *fgets ( char *str, int n, FILE *fp );
- str Is a character array
- n For the number of characters to read
- fp For file pointer .
- Return value : Return the first address of character array when reading successfully , That is to say str; Returns when the read fails NULL; If the internal pointer of the file has already pointed to the end of the file when reading begins , Then you won't be able to read any characters , Also returned NULL.
About fgets() A few caveats
- fgets() When it comes to line breaks , The newline character will be read into the current string . and gets() Dissimilarity , It ignores line breaks .
- The read string will be at the end Automatic addition ‘\0’,n One character also includes ‘\0’. in other words , Actually, it only reads n-1 Characters , If you want to read 100 Characters ,n The value of should be 101.
- need Key points Yes. , Reading into n-1 If it appears before characters Line break , Or read end of file , be End of read . That means , No matter n What is the value of ,fgets() Only one line of data can be read at most , You can't cross the line . stay C In language , There is no function to read files by line , We can With the help of fgets(), take n The value of is set large enough , One line of data can be read at a time .
int fputs( char *str, FILE *fp );
- str For the string to be written
- fp For file pointer
- Return value Write success, return non negative number , Failure to return EOF
Be careful :puts() Go to stdin Output with line feed
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define N 100
int main() {
FILE* fp;
char str[N+1];
if ((fp = fopen("text.txt", "r+")) == NULL) {
puts(" File opening failure ");
exit(0);
}
while (fgets(str,N,fp)!=NULL)
{
//Sleep(100);
printf("%s", str);
}
fclose(fp);
return 0;
}
Read files in binary mode
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );(C99 front )
size_t fread( void *restrict buffer, size_t size, size_t count,FILE *restrict stream );(C99 rise )
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );(C99 front )
size_t fwrite( const void *restrict buffer, size_t size, size_t count, FILE *restrict stream );(C99 rise )
- buffer Pointer to a memory block , It can be an array 、 Variable 、 Structure, etc .fread() Medium buffer Used to store the read data ,fwrite() Medium buffer Used to store the data to be written .
- size: Represents the number of bytes per data block .
- count: Indicates the number of data blocks to read and write .
- stream: Indicates the file pointer ( File stream ).
Return value : Returns the number of blocks successfully read and written ( Number of objects ), That is to say count. If the return value is less than count:
- about fwrite() Come on , There must be a write error , It can be used ferror() Function detection .
- about fread() Come on , May have read to the end of the file , An error may have occurred , It can be used ferror() or feof() testing .
- If an error occurs , Then the result value of the file position indicator of the stream is uncertain . If you read in some elements , Then the element value is uncertain .
Example
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
enum {
SIZE = 5 };
int main(void)
{
int a[SIZE] = {
1, 2, 3, 4, 5 };
FILE* fp1 = fopen("text.txt", "wb");
assert(fp1);
int tem = fwrite(a, sizeof(a[0]), SIZE, fp1);
printf(" Will succeed %d Write data to file \n", tem);
fclose(fp1);
int b[SIZE];
FILE* fp2 = fopen("text.txt", "rb");
assert(fp2);
tem = fread(b, sizeof b[0], SIZE, fp2);
fclose(fp2);
printf(" Successfully read in %d Data \n", tem);
for (int i = 0; i < SIZE; i++) {
printf("%d ", b[i]);
}
return 0;
}
Format read-write file
int fscanf ( FILE *fp, char * format, … );
int fprintf ( FILE *fp, char * format, … );
- fp For file pointer
- format Control string for format
- … Represents a list of parameters
- Return value fprintf() Returns the number of characters successfully written , If it fails, it returns a negative number .
- Return value fscanf() Returns the number of successfully assigned parameters in the parameter list .
And scanf() and printf() comparison , They only have one more fp Parameters .
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define N 2
struct stu {
char name[10];
int num;
int age;
float score;
} boya[N], boyb[N], * pa, * pb;
int main() {
FILE* fp;
fp = fopen("test.txt", "wt+");
assert(fp);
pa = boya;
for (int i = 0; i < N; i++) {
scanf("%s %d %d %f", pa->name, &(pa->num), &(pa->age), &(pa->score));
pa++;
}
pa = boya;
for (int i = 0; i < N; i++) {
fprintf(fp, "%s %d %d %f\n", pa->name, pa->num, pa->age, pa->score);
pa++;
}
rewind(fp);// Move the file position indicator to the beginning of a given file stream .
pb = boyb;
for (int i = 0; i < N; i++) {
fscanf(fp, "%s %d %d %f\n", pb->name, &(pb->num), &(pb->age), &(pb->score));
pb++;
}
pb = boyb;
for (int i = 0; i < N; i++) {
printf("%s %d %d %f\n", pb->name, pb->num, pb->age, pb->score);
pb++;
}
fclose(fp);
return 0;
}
Read and write files at random
The file reading and writing functions described above are sequential reading and writing , That is, reading and writing files can only start from scratch , Read and write data in sequence . But in the actual development, we often need to read and write the middle part of the file , To solve this problem , You have to move the position pointer inside the file first , Read and write again . This way of reading and writing is called random reading and writing , That is, start reading and writing from anywhere in the file .
The key to random reading and writing is to move the position pointer as required , This is called file positioning .
void rewind ( FILE *fp ); Used to move the position pointer to the beginning of the file
int fseek ( FILE *fp, long offset, int origin ); Used to move the position pointer to any position
- fp For file pointer , That is, the moved file .
- offset For offset , That is, the number of bytes to be moved . The reason is long type , I want to move more , Can handle larger files .offset Positive timing , Move backward ;offset When it is negative , Move forward .
- origin Is the starting position , That is, where to start calculating the offset .C The starting position specified by the language is Three , At the beginning of the file 、 Current location and end of file
Each position is represented by a corresponding constant :
- The starting point —— Constant names —— Constant values
- Beginning of file SEEK_SET 0
- The current position SEEK_CUR 1
- end of file SEEK_END 2
Be careful : fseek() Generally used for binary files , In the text file due to the need for conversion , The calculated position can sometimes go wrong .
Example :
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//ftell Returns the current file location indication
//
//fgetpos Get file location indicator
//
//fseek Move the file location indicator to the specified location in the file
//
//fsetpos Move the file location indicator to the specified location in the file
//
//rewind Move the file position indicator to the beginning of the file
#define N 3
struct stu {
char name[10]; // full name
int num; // Student number
int age; // Age
float score; // achievement
}boys[N], boy, * pboys;
int main() {
FILE* fp;
pboys = boys;
fp = fopen("test.txt", "w+");
puts("Input data:\n");
for (int i = 0; i < N; i++) {
scanf("%s %d %d %f", pboys->name, &pboys->num, &pboys->age, &pboys->score);
pboys++;
}
pboys = boys;
fwrite(pboys, sizeof(struct stu), N, fp);
rewind(fp);
fseek(fp, sizeof(struct stu), SEEK_SET);
fread(&boy, sizeof(struct stu), 1, fp);
printf("%s %d %d %f", boy.name, boy.num, boy.age, boy.score);
fclose(fp);
return 0;
}
C Language implementation file copy
#include "stdio.h"
#include "stdlib.h"
int main(int arg,char* argv[]){
if(arg!=3){
printf("input error!");
exit(0);
}
FILE* fpr = fopen(argv[1],"rb");
FILE* fpw = fopen(argv[2],"wb");
if(fpr==NULL||fpw==NULL) return 1;
fseek(fpr,0,SEEK_END);
int len = ftell(fpr);
rewind(fpr);
for(int i = 0;i<len;i++){
char ch = fgetc(fpr);
fputc(ch,fpw);
}
fclose(fpr);
fpr = NULL;
fclose(fpw);
fpw = NULL;
return 0;
}
Get file length
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int main(){
FILE* fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
rewind(fp);
printf(" The length of the file is :%d", len);// In file 0D 0A
return 0;
}
reference
边栏推荐
- Submission lottery - light application server essay solicitation activity (may) award announcement
- Principle of SSM framework
- sql刷题627. 变更性别
- Tutorial on principles and applications of database system (006) -- compiling and installing MySQL 5.7 (Linux Environment)
- Buuctf gold III
- IM即时通讯开发万人群聊消息投递方案
- 怎麼用MySQL語言進行行列裝置?
- 【Hot100】20. Valid parentheses
- [daily question] 1175 Prime permutation
- 嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
猜你喜欢

Tutorial on the principle and application of database system (003) -- MySQL installation and configuration: manually configure MySQL (Windows Environment)

EndeavourOS移动硬盘安装

Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)

IM即時通訊開發實現心跳保活遇到的問題

程序员职业生涯真的很短吗?

Principle of motion capture system
![[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting](/img/82/3bb382893682a30e8af130365ec4ef.jpg)
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting

Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!

数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)

Template Engine Velocity Foundation
随机推荐
Origin2018安装与使用(整理中)
How to cancel automatic search and install device drivers for laptops
Detailed explanation of activity life cycle and startup mode
ssm框架原理
Is the programmer's career really short?
C语言输入/输出流和文件操作
sql刷题586. 订单最多的客户
怎麼用MySQL語言進行行列裝置?
Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
【Kotlin】高阶函数介绍
Activity的生命周期和启动模式详解
免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
Virtual serial port simulator and serial port debugging assistant tutorial "suggestions collection"
如何使用phpIPAM来管理IP地址和子网
Go 语言怎么使用对称加密?
Motion capture system for apple picking robot
Rhcsa Road
数据库系统原理与应用教程(001)—— MySQL 安装与配置:MySQL 软件的安装(windows 环境)
How to restore the system with one click on Lenovo laptop