C file operations-writing statistics to the file header

Source: Internet
Author: User
Tags strtok

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.