Linux Control (statistics) file generation of C code implementation _c language

Source: Internet
Author: User
Tags reserved

This article shares the Linux control (statistics) file generated by the C code implementation case, for your reference, the specific contents are as follows

I. Description of requirements
It is required to write a program to count the total number of records in all files in the directory and the earliest and latest end times of all records in a directory that is not scheduled to be placed in a file in a Linux machine.

For example, there are two files Test_1.txt and test_2.txt in the directory, where Test_1.txt file contents are:

    • 15696192591|15696192592|20151103 120909|20151103 201545|
    • 15696192593|15696192594|20151103 110909|20151103 191545|
    • 02344273522|02344273523|20160108 110909|20160109 091545|

The contents of the Test_2.txt file are:

    • 15696192595|15696192596|20151102 120909|20151104 201545|
    • 15696192597|15696192598|20151101 110909|20151103 191545|

That is, the format of each record in the file is: Call number | called number | call start Time | Call end Time |, require generated control file CtlFile.txt content is:

    • 20151101 110909|20160109 091545|5|

That is, the minimum value of the start time for five records in the Test_1.txt and test_2.txt two files is "20151101 110909", the maximum end time is "20160109 091545", and 5 records are currently processed. In other words, the format of the control file is: Call Start time Minimum | call end time Maximum | Record total number of bars |.

Second, the program code
This program consists of three code files: main.c, ctlfilecreate.c and CtlFileCreate.h, with the following specific code:

Main.c

/**********************************************************************
* All rights reserved (C) 2016, Zhou Zhaoxiong.
*
* file name: ctlfilecreate.c
* file ID: no
* Content Summary: File in the directory to read and control the generation of files
* Other notes: No
* Current version: V1.0
* Completion Date: 20160109
*
**********************************************************************/
#include "CtlFileCreate.h"

/**********************************************************************
* Function Description: main function
* Input Parameters: no *
OUTPUT parameters: No *
return value: no *
Other Description: No
* Modified Date    version number modify the      content
*------------- ------------------------------------------------------
* 20160109    V1.0   Zhou Zhaoxiong    created
***********************************************************************/

INT32 Main ()
{
  readctlfile ();  Obtain the control file storage path, the control file full path name and the file Content field value

  readsrcfileandwritectlfile ();  Scan source file directory and write control file return

  0;


CtlFileCreate.h

/********************************************************************** * All rights reserved (C) 2015, Zhou Zhaoxiong. * * File name: CtlFileCreate.h * File ID: no * Content summary: File in the directory to read and control the generation of files * Other notes: no * current version: V1.0 * Completion Date: 20151102 * ************************* /#include <stdio.h> #include <stdlib.h> #include <
string.h> #include <dirent.h>//data type redefine typedef unsigned char UINT8;
typedef unsigned short int UINT16;
typedef unsigned int UINT32;
typedef signed INT INT32;

typedef unsigned char BOOL; Parameter type #define MML_INT8_TYPE 0 #define MML_INT16_TYPE 1 #define MML_INT32_TYPE 2 #define MML_STR_TYPE 3 #defin e TRUE (BOOL) 1 #define FALSE (BOOL) 0//field maximum length #define Max_ret_buf_len 1024//source file field structure typedef struct {UINT
  8 szsrcnumber[50];
  UINT8 SZDSTNUMBER[50]; 
  UINT8 SZDATASTARTTIME[50]; 
UINT8 SZDATAENDTIME[50];

} t_srcfilecontent;
function declares void sleep (UINT32 ICOUNTMS);
void Readctlfile (void); void ReadsrcfileandwriTectlfile (void);
void Getsrcfilecontentandwritectlfile (UINT8 *pszsrcfilename);
void Getsrcfilefieldvalue (UINT8 *pszcontentline, t_srcfilecontent *ptsrcfilecontent);
void Getctlfilecontentandwrite (T_srcfilecontent *ptsrcfilecontent, UINT8 *pszcontentbuffer); BOOL getvaluefromstr (UINT16 iserialnum, UINT8 icontenttype, UINT8 *psourcestr, UINT8 *pdststr, UINT8 cisolater, UINT32 iDs
Tstrsize);
void Removelineend (UINT8 *pszstr);

 void Writetoctlfile (UINT8 *pszcontentline);

ctlfilecreate.c

/********************************************************************** * All rights reserved (C) 2015, Zhou Zhaoxiong. * * File name: CTLFILECREATE.C * File ID: no * Content summary: File in the directory to read and control the generation of files * Other notes: no * current version: V1.0 * Completion Date: 20151102 * *************************     /#include "CtlFileCreate.h"//global variable UINT8 g_szsourcedir[500] = {0};     The source directory to be scanned UINT8 g_szctlfiledir[500] = {0};     The stored directory of the generated control file UINT8 g_szsourcebakdir[500] = {0};     The backup directory of the source file after processing UINT8 g_szctlfilename[256] = {0};     Control file full path name UINT8 g_szdatastarttime[50] = {0};     The earliest start time of data records in all source files UINT8 g_szdataendtime[50] = {0};      The latest end time for data records in all source files UINT32 g_irecordssum = 0; Total number of records processed/********************************************************************** * Function Description: Read the start time in the control file, End time and number of records * input parameter: no * output parameter: no * return value: No * other Description: No * Modified Date version number modify the content *------------------------------------ ------------------------------* 20151102 V1.0 Zhou Zhaoxiong created **********************/void Readctlfile (void) {UINT8 *pszhomepath = NULL;
  FILE *fpctlfile = NULL; 

  UINT8 szbuf[500] = {0};
  Read the start time, end time, and number of records in the control file, and if the program restarts on the same day, the number of record bars continues to number Pszhomepath = getenv ("Home");
  if (Pszhomepath = = NULL) {return; snprintf (G_szctlfiledir, sizeof (G_szctlfiledir)-1, "%s/zhouzhaoxiong/zzx/ctlfilecreate/ctlfile", PszHomePath); Control file storage Directory snprintf (g_szctlfilename, sizeof (G_szctlfilename)-1, "%s/ctlfile.txt", G_szctlfiledir);
  Control file Full path name fpctlfile = fopen (G_szctlfilename, "R");

    if (fpctlfile!= NULL) {fgets (szbuf, sizeof (SZBUF), fpctlfile); Gets the start time g_szdatastarttime if (TRUE!= getvaluefromstr (1, Mml_str_type, szbuf, G_szdatastarttime, ' | '), sizeof (G_szdata
      StartTime)) {printf ("readctlfile:exec getvaluefromstr to get G_szdatastarttime failed!\n");
    Return //Get End time G_szdataendtime if (TRUE!= getvaluefromstr (2, Mml_str_type, Szbuf, G_szdataendtime, ' | ', sizeof (G_szdataendtime)) {printf ("readctlfile:exec getvaluefromstr to get G_szdataendtime failed!\n");
    Return //Get the number of records G_irecordssum if (TRUE!= getvaluefromstr (3, Mml_int32_type, Szbuf, (UINT8 *) &g_irecordssum, ' | ',
      sizeof (G_irecordssum)) {printf ("readctlfile:exec getvaluefromstr to get g_irecordssum failed!\n");
    Return
    } fclose (Fpctlfile);

    Fpctlfile = NULL; printf ("readctlfile:datastarttime=%s, dataendtime=%s, recordssum=%d\n", G_szdatastarttime, G_szdataendtime, g_
  Irecordssum);
}/********************************************************************** * Function Description: Scan source file directory, and write control file * Input parameters: no * output parameters: None 
* Return value: No * other Description: No * Modified Date version number modify the content *------------------------------------------------------------------ * 20151102 V1.0 Zhou zhaoxiong create ********************************************************************/void R 
  Eadsrcfileandwritectlfile (void) {UINT8 *pszhomepath = NULL; UINT8SZCOMMANDBUF[500] = {0}; 

  UINT8 szsrcfile[500] = {0};
  DIR *pdir = NULL;

  struct Dirent *pdirent = NULL;
  Pszhomepath = getenv ("Home");
  if (Pszhomepath = = NULL) {return;   snprintf (G_szsourcedir, sizeof (G_szsourcedir)-1, "%s/zhouzhaoxiong/zzx/ctlfilecreate/srcfile", PszHomePath); Source file storage Directory snprintf (g_szsourcebakdir, sizeof (G_szsourcebakdir)-1, "%s/zhouzhaoxiong/zzx/ctlfilecreate/srcfile_bak" , Pszhomepath);
    Source file backup directory while (1) {Pdir = Opendir (G_szsourcedir);
      if (NULL = = Pdir) {printf ("Readsrcfileandwritectlfile:pdir is null!\n");
    Continue while ((pdirent = Readdir (pdir))!= NULL)//scan source directory, get filename {if strncmp (Pdirent->d_name, "Test_", str
        Len ("Test_")) = = 0////If the prefix of the source file is matched, read the contents of the file and write the control file {memset (szsrcfile, 0x00, sizeof (szSrcFile));
        snprintf (szSrcFile, sizeof (szSrcFile)-1, "%s/%s", G_szsourcedir, Pdirent->d_name, G_szsourcebakdir); GetsrcfilecontentandwriTectlfile (szSrcFile);
        Gets the contents of the source file and writes the control file//process complete, cut the file to the backup directory memset (szcommandbuf, 0x00, sizeof (SZCOMMANDBUF));
        snprintf (szcommandbuf, sizeof (SZCOMMANDBUF)-1, "MV%s%s", szSrcFile, G_szsourcebakdir);
        System (SZCOMMANDBUF);
      printf ("Readsrcfileandwritectlfile:now, move%s to%s\n", Pdirent->d_name, G_szsourcebakdir);
    } closedir (Pdir);

    Pdir = NULL;  Sleep (60 * 1000); Scan every 1 minutes}/********************************************************************** * Function Description: Get the content in the source file and write the control file * input Parameters: pszsrcfilename-with path source filename * Output parameter: no * return value: No * other Description: No * Modified Date version number modify the content *---------------------------- --------------------------------------* 20151102 V1.0 Zhou Zhaoxiong created **************************************
  /void Getsrcfilecontentandwritectlfile (UINT8 *pszsrcfilename) {FILE *FP = NULL;

  UINT8 szcontentline[1024] = {0}; T_srcfilecontent TsrcfileconteNT = {0};
    if (Pszsrcfilename = = NULL) {printf ("Getsrcfilecontentandwritectlfile:pdir is null!\n");
  Return } if (fp = fopen (Pszsrcfilename, "r") = = NULL)//read-only mode open {printf ("Getsrcfilecontentandwritectlfile:open src F
    Ile failed!\n "); 
  Return else {while (feof (fp) = = 0 && ferror (fp) = 0) {//each row corresponds to a source file record memset (szcontentline, 0
      x00, sizeof (Szcontentline)); if (fgets (szcontentline, sizeof (szcontentline), fp) = = NULL) {printf ("Getsrcfilecontentandwritectlfile:exe
      C fgets to get line null.\n ");
      else {printf ("Getsrcfilecontentandwritectlfile:get Content line:%s\n", szcontentline); } removelineend (Szcontentline); Remove the carriage return line break after the string if (strlen (szcontentline) = = 0)///If blank, continue processing the next {printf ("Getsrcfilecontentandwr 
        Itectlfile:the length of Contentline is 0, continue.\n ");
      Continue } getsrcfilefieldvalue (Szcontentline, &tsrcfilecontent);
      Gets the value of each field in a record memset (Szcontentline, 0x00, sizeof (Szcontentline)); Getctlfilecontentandwrite (&tsrcfilecontent, szcontentline);  Assemble the contents of the Write Control file Writetoctlfile (szcontentline);
    Write the content to the control file} fclose (FP);
  fp = NULL; }/********************************************************************** * Feature Description: Assembly write Control file content * Input parameters: ptsrcfilecontent-the value of each field in a record in the source file * Output parameter: pszcontentbuffer-cache of Content * return value: No * Other Description: Control file is recorded as: datastarttime| dataendtime|
recordssum|   * Modify the date version number modify the content *------------------------------------------------------------------* 20151102 V1.0 Zhou Zhaoxiong Create ********************************************************************/void GetCtlFileContentAndWr

  ITE (t_srcfilecontent *ptsrcfilecontent, UINT8 *pszcontentbuffer) {UINT8 szcontentline[500] = {0}; if (ptsrcfilecontent = null | | pszcontentbuffer = = NULL) {printf ("getctlfilecontentandwrite:ptsrcfilecontent or P SzcontentBuffer is null!\n ");
  Return
  Srcfilecontent->szdatastarttime, strlen (ptsrcfilecontent->szdatastarttime)); else {if (strncmp g_szdatastarttime, Ptsrcfilecontent->szdatastarttime, strlen (ptsrcfilecontent->szdatast

      arttime)) > 0)///modified to minimum time {memset (g_szdatastarttime, 0x00, sizeof (g_szdatastarttime));
    strncpy (G_szdatastarttime, Ptsrcfilecontent->szdatastarttime, strlen (ptsrcfilecontent->szdatastarttime));
  Cfilecontent->szdataendtime, strlen (ptsrcfilecontent->szdataendtime)); else {if (strncmp g_szdataendtime, Ptsrcfilecontent->szdataendtime, strlen (ptsrcfilecontent->szdataendtim E) < 0)//modified to Maximum time {memset (g_szdataendtime, 0x00, sizeof (G_szdataendtime));
    strncpy (G_szdataendtime, Ptsrcfilecontent->szdataendtime, strlen (ptsrcfilecontent->szdataendtime));   }///record total number of bars plus 1 g_irecordssum = g_irecordssum + 1;  Total number of records per day plus 1//Print three field content printf ("Getctlfilecontentandwrite:datastarttime is%s, Dataendtime is%s, Recordssum is"

  %d\n ", G_szdatastarttime, G_szdataendtime, g_irecordssum); Assemble the message content written to the control file snprintf (szcontentline, sizeof (Szcontentline)-1, "%s|%s|%d|", G_szdatastarttime, G_szdataendtime, G

  _irecordssum);

  printf ("Getctlfilecontentandwrite:contentline is%s\n", szcontentline);
strncpy (Pszcontentbuffer, Szcontentline, strlen (Szcontentline)); /********************************************************************** * Feature Description: Gets the value of each field in the source file * Input parameters: pszcontentline-a record * output parameter: ptsrcfilecontent-value of each field in a record in the source file * return value: No * Other Description: The format of each record in the source file is: srcnumber| dstnumber| datastarttime|
dataendtime| * Modify the date version number modify the content *------------------------------------------------------------------* 20151102     V1.0 Zhou zhaoxiong Create ********************************************************************/void GetSrcFileFi Eldvalue (UINT8 *pszcontentline, t_srcfilecontent *ptsrcfilecontent) {if (Pszcontentline = NULL | | ptsrcfilecontent = =
    NULL) {printf ("Getsrcfilefieldvalue:contentline or srcfilecontent is null!\n");
  Return //Get Source number if (TRUE!= getvaluefromstr (1, Mml_str_type, Pszcontentline, Ptsrcfilecontent->szsrcnumber, ' | '), sizeof
  (Ptsrcfilecontent->szsrcnumber)))
    {printf ("getsrcfilefieldvalue:exec getvaluefromstr to get Szsrcnumber failed!\n");
  Return //Get the destination number if (TRUE!= getvaluefromstr (2, Mml_str_type, Pszcontentline, Ptsrcfilecontent->szdstnumber, ' | '), SIZEO F (ptsrcfilecontent->szdstnumber)) {printf ("getsrcfilefieldvalue:exec getvaluefromstr to get Szdstnumber failed
    !\n ");
  Return //Get Start time if (TRUE!= getvaluefromstr (3, Mml_str_type, Pszcontentline, Ptsrcfilecontent->szdatastarttime, ' | '), s IzeOf (Ptsrcfilecontent->szdatastarttime)) {printf ("getsrcfilefieldvalue:exec getvaluefromstr to get SzDataStartTi
    Me failed!\n ");
  Return //Get End time if (TRUE!= getvaluefromstr (4, Mml_str_type, Pszcontentline, Ptsrcfilecontent->szdataendtime, ' | ', siz EOF (Ptsrcfilecontent->szdataendtime))) {printf ("getsrcfilefieldvalue:exec getvaluefromstr to get Szdataendtime
    Failed!\n ");
  Return printf ("getsrcfilefieldvalue:srcnumber=%s, dstnumber=%s, datastarttime=%s, dataendtime=%s\n", ptSrcFileContent- >szsrcnumber, Ptsrcfilecontent->szdstnumber, Ptsrcfilecontent->szdatasta


Rttime, Ptsrcfilecontent->szdataendtime); /********************************************************************** * Feature Description: Program hibernate * input parameter: icountms-sleep time (unit: MS) * lost Out parameters: No * return value: No * other Description: No * Modified Date version number modify the content *-----------------------------------------------------------    -------* 20151102 V1.0 Zhou Zhaoxiong  Create ********************************************************************/void Sleep (UINT32 icountms) {struct timeval

  T_timeout = {0};
    if (Icountms < 1000) {t_timeout.tv_sec = 0;
  t_timeout.tv_usec = Icountms * 1000;
    else {t_timeout.tv_sec = icountms/1000;
  t_timeout.tv_usec = (ICOUNTMS% 1000) * 1000;  Select (0, NULL, NULL, NULL, &t_timeout); Call select function Blocking program}/********************************************************************** * Feature description: Gets the value of a field in a string * Input parameters: iserialnum-field number (positive integer) icontenttype-the type of content that needs to be fetched psourcestr-the source string pdststr-the destination string (where the extracted value is stored) Cisola Ter-the delimiter of the field in the source string idststrsize-the length of the destination string * OUTPUT parameter: no * return value: true-success false-Failure * Other Description: No * Modified Date version number modify the content *------ --------------------------------------------------------* 20151102 V1.0 Zhou Zhaoxiong created ********************* /BOOL Getvaluefromstr (UINT16 iserialnum, UINT8 Icontenttype, UINT8 *PSOURCEstr, UINT8 *pdststr, UINT8 cisolater, UINT32 idststrsize) {UINT8 *pstrbegin = NULL;
  UINT8 *pstrend = NULL;   UINT8 Szretbuf[max_ret_buf_len] = {0};
  The intercepted string is placed in the array UINT8 *puint8 = NULL;
  UINT16 *puint16 = NULL;
  UINT32 *puint32 = NULL;   UINT32 Ifieldlen = 0;
  Used to represent the actual length of each field if (Psourcestr = NULL)//To judge the exception of the input pointer {return FALSE;
  }//Field first pstrbegin = Psourcestr;
    while (--iserialnum!= 0) {pstrbegin = STRCHR (Pstrbegin, Cisolater);
    if (Pstrbegin = = NULL) {return FALSE;
  } Pstrbegin + +;
  }//Field tail pstrend = STRCHR (Pstrbegin, Cisolater);
  if (pstrend = = NULL) {return FALSE;
  } Ifieldlen = (UINT16) (Pstrend-pstrbegin);
  if (Ifieldlen >= Max_ret_buf_len)//For exception protection, prevents the value of each field from being too long {ifieldlen = max_ret_buf_len-1;

  } memcpy (Szretbuf, Pstrbegin, Ifieldlen); Place the required field values in the PDSTSTR to switch (icontenttype) {case Mml_str_type://String Type {strncpy (pdststr, Szretbuf, idststrsize);
    Break
      Case Mml_int8_type://character type {pUINT8 = (UINT8 *) pdststr;
      *pdststr = (UINT8) atoi (SZRETBUF);
    Break
      Case Mml_int16_type://Short int type {pUINT16 = (UINT16 *) pdststr;
      *puint16 = (UINT16) atoi (SZRETBUF);
    Break
      Case MML_INT32_TYPE://int type {pUINT32 = (UINT32 *) pdststr;
      *puint32 = (UINT32) atoi (SZRETBUF);
    Break
    } default://must have default branch {return FALSE;
} return TRUE;
/********************************************************************** * Function Description: Remove the return line feed character after the string * input parameter: pszstr-input string * OUTPUT Parameters: No * return value: No * other Description: No * Modified Date version number modify the content *-------------------------------------------------------- ----------* 20151102 V1.0 Zhou Zhaoxiong created ****************************************************************** **/void RemovelineEnd (UINT8 *pszstr) {UINT32 Istrlen = 0;
    if (pszstr = = NULL) {printf ("Removelineend:pszstr is null!\n");
  Return
  } Istrlen = strlen (PSZSTR);  while (Istrlen > 0) {if (pszstr[istrlen-1] = ' \ n ' | | | pszstr[istrlen-1] = = ' \ r ') {pszstr[istrlen-1] =
    ' I ';
    } else {break;
  } Istrlen--;
} return; /********************************************************************** * Function Description: Write the content to the control file * Input parameters: pszcontentline- File record * OUTPUT parameter: no * return value: No * other Description: No * Modified Date version number modify the content *------------------------------------------------ ------* 20151103 V1.0 Zhou Zhaoxiong created ***********************************************************************

  /void Writetoctlfile (UINT8 *pszcontentline) {FILE *fpctlfile = NULL;
    if (Pszcontentline = = NULL) {printf ("Writetoctlfile:pszcontentline is null.\n");
  Return
  } fpctlfile = fopen (G_szctlfilename, "w"); if (fpctlfile!= NULL) {fputs (PszcoNtentline, Fpctlfile);
    Fclose (Fpctlfile);

    Fpctlfile = NULL; printf ("Writetoctlfile:write ctl file successfully!
  file=%s, content=%s\n ", G_szctlfilename, Pszcontentline); else {printf ("Writetoctlfile:write ctl file failed!
  file=%s, content=%s\n ", G_szctlfilename, Pszcontentline);

 }
}

Compiling and running of the program
Upload the program code to the Linux machine, uploading some source files that satisfy the naming specification in the current user's Zhouzhaoxiong/zzx/ctlfilecreate/srcfile directory, and then use the Gcc-g-o ctlfilecreate The MAIN.C ctlfilecreate.c command compiles the program, generates a "ctlfilecreate" file, and then runs the "ctlfilecreate" command, which can be seen in the current user's zhouzhaoxiong/zzx/ There is a control file generation under the Ctlfilecreate/ctlfile directory, and a backup file of the source files is generated under the current user's Zhouzhaoxiong/zzx/ctlfilecreate/srcfile_bak directory.

View the contents of the control file, which records the total number of records in all files currently being processed and the maximum call start time and call end time in all records.

Iv. Procedural notes
first, in order to facilitate the description, in this program, the source file prefix is "Test_", the control file named "CtlFile.txt". In the actual development, everyone can use the configuration items to determine the source file and control file naming rules.

Second, to prevent the source files from being processed repeatedly, when a source file is processed, it is clipped to the backup directory. This is also done to facilitate proofreading of the contents of the control file later.

Third, when you read the first record in the file, the call start time and call end time in this record are stored in two global variables, and the control file is written in the format, and the call start time and call end time in the record are compared to the global variables when reading other records in the file. Make sure that the global variables contain the minimum call start time and call end time, record the total number of bars plus 1, and write the new record contents to the control file.

Four, after processing all the files in the current directory, the program sleeps for a period of time and then continues to scan the directory. In actual development, the hibernation interval can also be configured.

The above is the entire content of this article, I hope to help you learn.

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.