C/C + + programs read (save) data from text files

Posted by bqheath on Sat, 26 Feb 2022 16:20:47 +0100

  • In C program:

When dealing with data (files) outside the program code, we use the concept of stream to realize the data exchange between the process's virtual memory and files.

——FILE stream: the C standard library provides FILE (named FILE because linux treats all mechanisms as files). The FILE object is a structure that contains all the information needed to manage the stream, including buffer information, various tags (such as FILE end tag and error tag), and FILE descriptors for actual I/O.

——Input stream: data transferred from file to memory is called input stream, and data transferred from memory to file is called output stream.

——Open FILE: FILE object through call fopen Function. For example: FILE *fp, fp=fopen("filename","r"), which means that the file stream related to filename is established in a read-only manner; Filename is the relative pathname in the current directory, and r stands for readable (the mode of opening the file).  

1: Read

1: For reading some files with standard format, you can use the standard library stdio Under H fscanf Function,

The function prototype is: int fscanf(FILE * stream, const char * format, [argument...])

For example, read the file data Txt (relatively standard data format)

Code implementation reading:

//test.c
//File reading
  #include<stdio.h>
  
  int main()
  {
    //1: Create a file stream. If the file pointer name = fopen (file name, using file mode) fails to open, NULL will be returned;
    FILE *fp=fopen("./data.txt","r"); //In data Txt file as an example

    //2: Check whether the file is opened successfully;
    if(!fp){
       printf("Failed to open!\n");
       return -1; //Return exception
    }
    //3:
    int num; //Used to store an integer data
    char name[10], place[10]; //Used to store two string data

    //Abstract understanding:
    //Understand the meaning of file location: it represents the position of the current readable and writable characters of the open file, which is expressed as an integer to the file header;
    //fscanf can understand this when reading data: after the file is opened, it becomes an unordered byte stream (water stream), which will flow to the read end through a pipe;
    //After learning about fscanf, we know that it will stop when it encounters space characters (spaces, tabs) and line breaks. The stop here can be understood as:
    //Stop to do a separation operation for two unrelated data blocks in the file, which just adapts to the behavior that we generally use empty characters (including newline characters) as the separation between two data;
    //We just need to understand both ends of the pipe
    //The position at one end of the pipeline is the position of the file, indicating the position that has been read.
    //One end of the outflow pipeline is the end used by the process to read data. It can read the distinguished data in the pipeline.
   
   //4: Read:
    fscanf(fp,"%d%s%s",&num, name,place); //fscanf format read of convection.
    //Note 1: fscanf (FP, ""% Da% s% s ", & num, name, place); Data can be: 1a Xiaogang Henan; The accurate reading of indicates that a is the boundary between the two data.
    //Note 2: because the stream is a pointer, the function is to give the first address of each data block to the corresponding parameter, so num needs to & get the address,
    //Note 3: since name and place have already expressed addresses, they need not be changed;

    fscanf(fp,"\n");
    //\n is the control character, and the position of the file is at the beginning of the second line;

    //Then operate: fscanf (FP, ""% d% s% s ", & num, name, place); You can continue to read the second line
    //Therefore, we often only need to use a while statement to read the whole file into a data structure (process)
    /*
    while(!feof(fp)) //feof()Check whether a file ends, that is, it reaches the end of the file. If it ends, it returns a non-0 value, otherwise it returns 0
    {
       fscanf(fp,"%d%s%s\n",&num, name,place); 
    }
    */
 
    //Test read results
    printf("%d %s %s\n",num, name, place);
 
    //Close flow
    fclose(fp); 
    
    return 0;

 }
​

Program running results:

2: Read the whole line of data from the file (under standard library stdio.h) fgets)

Function prototype: char *fgets(char *str, int n, FILE *stream);  

It reads a line from the specified stream and stores it in the string pointed to by str. When (n-1) characters are read, or line breaks are read, or the end of the file is reached, it will stop, and it will not stop when encountering spaces;

Example: read a line of data from a file:

Code implementation:

//test3.c
//Line read file data

#include<stdio.h>
#define maxlen 30

int main()
{
    //Create file stream
    FILE *fp=fopen("./data.txt","r");
    
    //2: Check whether the file is opened successfully;
    if(!fp){
       printf("Failed to open!\n");
       return -1; //Return exception
    }
    char str[maxlen];//Buffer for storing data

    //Read a line of data from the file and store it to the address starting from str, with the maximum length of maxlen, and then start the next reading from the downlink
    //If the data of this row is longer than maxlen-1, only one incomplete row can be returned, and the next call starts from there
    fgets(str,maxlen,fp);

    //detection result 
    printf("%s\n",str);

    //Close flow
    fclose(fp);
    return 0;

}

Operation results:

2: Preserve

1: Saving and reading are often related. The saving format determines the way you read. Use functions fprintf You can save in the specified format:

The function prototype is: int fprintf (file * stream, const char * format, [argument]...)  

Suppose you save a person's personal information to a file:

 

/*test2.c */
//Data saving

#include<stdio.h>

int main()
{
    //Example: a person's information
    int num=1;
    char name[10]="Xiao Ming";
    char place[10]="Henan";

    //Establish flow with files
    FILE *fp=fopen("./data.txt","w");
    
    //2: Check whether the file is opened successfully;
    if(!fp){
       printf("Failed to open!\n");
       return -1; //Return exception
    }

    //Format and output the data to the specified file stream, int fprintf (file * stream, const char * format, [argument]...) 
    //Note: this function writes the format string to the specified output stream. Format includes one or more of space characters, non space characters and specifiers. For example: fprintf(fp, ""); Is to enter spaces into the stream.
    //It can be understood that the process prints the data (fprintf) into the file with the help of the stream;

    //Write the personal information into the specified stream, separate the data with a space, and finally write a newline character (control character).
    fprintf(fp,"%d %s %s\n",num, name,place);

    //Therefore, it is often possible to write a table (linked list, sequential table) into the output stream in a specified row format as long as a while statement is used
    /*
    while(!feof(fp)) //feof()Check whether a file ends, that is, it reaches the end of the file. If it ends, it returns a non-0 value, otherwise it returns 0
    {
       fprintf(fp,"%d %s %s\n",num, name,place); 
    }
    */
    //Close flow
    fclose(fp);

    return 0;

}

Operation results:

2: Write a string into the stream (fputs). Function prototype: int fputs(const char *str, FILE *stream);

Example:

//test4.c
//Save string

#include<stdio.h>

int main()
{
    //1: Create a file stream. If the file pointer name = fopen (file name, using file mode) fails to open, NULL will be returned;
    FILE *fp=fopen("./data.txt","a"); //In data Txt file as an example, a means append

    //2: Check whether the file is opened successfully;
    if(!fp){
       printf("Failed to open!\n");
       return -1; //Return exception
    }

    //string
    char string[20]="Facing the world";

    //write string to the fstream
    fputs(string,fp);

    //Close flow
    fclose(fp);

    return 0;

}

Operation results:

On c + +:

In c + +, we can use the operators <, > > to read and write the stream, which is more convenient and easy to understand;

Refer to the following examples for details:

1: Read the data shown:

Code implementation:

 

//c + + file reading
#Include < iostream > / / input / output stream
#/ / stream < fstream > >

//using namespace std; // If you use this declaration, you don't need to add STD::


int main()
{
   //Serial number, age, year;
   int num, age, year;
   //Name, address
   char name[20], place[20];

   //c + + file stream, ifstream is the input file stream
   std::ifstream fp;

   //Open is a member function of ifstream. Its function is to open a file and associate it with the stream
   fp.open("./data.txt",std::ios::in); //ios::in indicates the mode of reading stream and the open mode.

   //Member function is_open checks whether the stream has an associated file, that is, whether it is opened successfully or not. The success returns true and the failure returns false
   if(!fp.is_open()){
       std::cout<<"Failed to open file!!\n";
       return 1;       // Return exception;
   }

   //Read data
   fp>>num>>year>>age>>name>>place; //Use the operator > > to transfer the data to the corresponding variable

   //testing
   std::cout<<num<<":"<<name<<",age:"<<age<<",year:"<<year<<",live in:"<<place<<"\n"; //cout is equivalent to printf

   //Close flow
   fp.close();

    return 0;
}

Operation results:

2: Save data to file:

Example: save a person's specific information to the file data Txt

Code implementation:

 

//c + + data saving
#Include < iostream > / / input / output stream
#/ / stream < fstream > >

//using namespace std; // If you use this declaration, you don't need to add STD::


int main()
{
   //Serial number, age, year;
   int num=3;
   int age=20;
   int year=1993;
   //Name, address
   char name[20]="Bruce Lee";
   char place[20]="Guangyuan";

   //c + + file stream, ofstream is the output file stream
   std::ofstream fp;

   //Open is a member function of ofstream. Its function is to open a file and associate it with a stream
   fp.open("./data.txt",std::ios::app); //ios::app indicates that every write is appended to the tail of the stream, indicating the open mode.

   //Member function is_open checks whether the stream has an associated file, that is, whether it is opened successfully or not. The success returns true and the failure returns false
   if(!fp.is_open()){
       std::cout<<"Failed to open file!!\n";
       return 1;       // Return exception;
   }

   //Read data
   fp<<num<<" "<<year<<" "<<age<<" "<<name<<" "<<place<<"\n"; //Use the operator < < to transfer each data to the file associated with the stream

   //Close flow
   fp.close();

    return 0;
}

Operation results:

Author: Haggle over every detail

source: Haggle over everything - blog Garden

Topics: C++ p2p GNU