c语言一个处理文本文件的例子

功能

读取一个文本文件,将其中的文本按规则转换为int数据,然后对数据进行处理。文本的格式类似36 565 233...

代码

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

const char delimiter[] = { ' ' };

u16 data[2100];

int ParseData(char *str)
{
    char *split = NULL;
    int i = 0;

    split = strtok(str, delimiter);

    while (1)
    {
        if (split != NULL)
        {
            data[i++] = atoi(split);
            split = strtok(NULL, delimiter);
        }
        else
        {
            return i;
        }
    }
}

int main(int argc, char **argv)
{
    FILE *fp = NULL;
    char tmp[100000];

    int counter = 0;
    int ch;
    int i;
    float index = 0;

    if (argc != 2)
    {
        printf("please enter the data path\n");
        return -1;
    }

    argv++;

    fp = fopen(*argv, "r");

    if (NULL == fp)
    {
        printf("file open Fail!\n");
        return -1;
    }

    do
    {
        /* read a char from the file */
        ch = fgetc(fp);
        tmp[counter++] = ch;
    } while (ch != EOF);


    counter = ParseData(tmp);

    // if(counter != 2080)
    // {
    //     printf("data amount is %d , should be 2080\n",counter);
    //     return -1;
    // }

    // for (i = 0; i < counter; i++)
    // {
    //     printf("%d ", data[i]);
    // }

    fclose(fp);

    fp = NULL;

//    GetCentroid(data,&index);

    printf("index = %0.1f \n",index);


    return 0;
}

解释

  1. 使用argv 传入文本路径
  2. 使用fopen打开文件,使用fgetc读取文本中的字符
  3. 使用strtok来分割字符
  4. 使用atoi来转换字符数据为整形数据

注意点

  1. 文本需要转换为ANSI编码
  2. 没有防错功能,需要确保文本输入没问题
  3. ch必须定义为整形,虽然fgetc返回char
  4. 文件使用完毕后需调用fclose
posted @ 2017-04-06 09:47  Weyne  阅读(927)  评论(0编辑  收藏  举报