There is a small requirement. The text file stores more than 10 fields, including user information, product information, and price information. Each field is separated by the symbol '|', for example, 9962519126 | 20120524143922 | Umai: PROG/330664@BESTV.SMG.SMG | City thieves [English] | null | 80 | 0 | 5 | 90002 | 0 | 2012052414412604 | 1 | 0 | 0
The first line is required to be the number of records | Total fee
Implementation Method: After combining the information of the file to be written, add 1 to the number of records, add the fee, write the first line, and then locate the cursor at the current end of the file, then write the information. This is a loop!
Simple code:
# Include "stdafx. h"
# Include <stdio. h>
# Include <string>
Int main (int argc, char * argv [])
{
Char Inf [3] [20] = {0 };
Char strs [3] [10];
Int I = 0;
Int iFeeSum = 0;
Int iCount = 0;
Int index = 0;
Char lz_Recond [20] = {0 };
Char temp [20] = {0 };
// User name | product name | fee
Strcpy (Inf [0], "you | 90002 | 100 \ n ");
Strcpy (Inf [1], "me | 90003 | 100 \ n ");
Strcpy (Inf [2], "she | 90004 | 100 \ n ");
Printf ("inf = % s \ n", Inf [0]);
FILE * fp = fopen ("Record.txt", "w ");
If (fp = NULL)
{
Printf ("Can not open MdnFile: % s \ n ");
Exit (-1 );
}
Printf ("inf = % s \ n", Inf [I]);
While (I <3)
{
Strcpy (temp, Inf [I]);
Char * p = strtok (temp, "|"); // separate the required fields.
While (p! = NULL)
{
Strcpy (strs [index], p );
P = strtok (NULL, "| ");
Index ++;
}
IFeeSum = iFeeSum + atoi (strs [2]);
ICount = iCount + 1;
Index = 0;
Sprintf (lz_Recond, "% d | % d \ n", iFeeSum, iCount );
Printf ("lz_Recond = % s \ n", lz_Recond );
Rewind (fp); // cursor positioned in the file header
Fputs (lz_Recond, fp );
Fseek (fp, 0, SEEK_END); // The cursor is located at the current position of the file.
Printf ("inf = % s \ n", Inf [I]);
Fputs (Inf [I], fp );
I ++;
}
Fclose (fp );
Return 0;
}
From the cancan8538 Column