Linux教程網
單行作為索引,雙行保存有數據,代碼如下
[cpp]
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- #define MAX_DB_SIZE 1000
-
- int database[MAX_DB_SIZE];
-
- const char *paramfile = "parameter.txt";
-
- int get_sum_line(const char *paramfile);
- void init_param(int database[], const char *paramfile, int sum_line);
-
- int main(int argc, char *argv[])
- {
- int sum = get_sum_line(paramfile);
- if (sum % 2 == 1)
- {
- printf("Parameter Error!\n");
- return -1;
- }
- else
- {
- init_param(database, paramfile, sum);
- return 0;
- }
- }
-
- int get_sum_line(const char *paramfile)
- {
- char c = 0;
- int linenum = 0;
- FILE *fp = NULL;
- int iNewLineFlag = 0;
-
- fp = fopen(paramfile, "r");
- if (fp == NULL)
- return -1;
-
- while ((c = fgetc(fp)) != EOF)
- {
- if (c == '\n')
- {
- linenum++;
- iNewLineFlag = 0;
- }
- else
- {
- iNewLineFlag = 1;
- }
- }
-
- if (iNewLineFlag)
- linenum++;
- printf("LineNum:%d\n", linenum);
- fclose(fp);
- return linenum;
- }
-
- void init_param(int database[], const char *paramfile, int sum_line)
- {
- FILE *fd;
- char line[255];
-
- int i = 0;
-
- if (!(fd = fopen(paramfile, "r")))
- {
- printf("Couldn't open parameter file %s.\n", paramfile);
- exit(-1);
- }
-
- memset(database, 0, sizeof(int) * MAX_DB_SIZE);
-
- unsigned int index_tmp;
- unsigned long data_tmp;
- unsigned int tmp;
- int loop_num = sum_line >> 1;
- for (i = 0; i < loop_num; i++)
- {
- index_tmp = 0;
- fgets(line, 254, fd);
- sscanf(line, "%x", &index_tmp);
- printf("index_tmp=%8X; ", index_tmp);
-
- data_tmp = 0;
- fgets(line, 254, fd);
- sscanf(line, "%x", &data_tmp);
- printf("data_tmp=%8X; \n", data_tmp);
- }
-
- fclose(fd);
- }
Copyright ©
Linux教程網 All Rights Reserved