C文件操作

来源:互联网 发布:linux chmod u s 编辑:程序博客网 时间:2024/06/05 00:11
#include <stdio.h>#include <string.h>#include <stdlib.h>#define Malloc(type,n) (type *)malloc((n)*sizeof(type))static char *line = NULL;static int max_line_len = 128;static char* readline(FILE *input){int len;if(fgets(line, max_line_len, input) == NULL)return NULL;while(strrchr(line,'\n') == NULL) //查找line字符串中是否含有\n,如果有,说明读取一行结束;如果没有,增加分配空间,继续读取{max_line_len *= 2;line = (char *) realloc(line,max_line_len);len = (int) strlen(line);if(fgets(line+len,max_line_len-len,input) == NULL)break;}return line;}int load_data(char * filename,  int  person_info[][7]){int index=0;int count=0;int i=0;char *p;FILE *fp = fopen(filename,"r");if(fp == NULL){return 0;}line = Malloc(char, max_line_len);while(readline(fp)!=NULL){p = strtok(line,","); person_info[count][index] = atoi(p);while(1){p = strtok(NULL,",");if(p == NULL || *p == '\n') /* 判断是否读到最后一个字符 */break;index++;person_info[count][index] = atoi(p);}index=0;count++;}free(line);fclose(fp);return count;}void main(){int PersonData[6][7]; load_data("female.txt", PersonData);}


以上代码即为读取文件的典型操作,最终将文本中的数据加载到一个二维数组中存储,其中涉及到关于文件操作和字符串操作的多个知识点:

1. 打开一个文件采用fopen()函数,第一个参数为文件全名,第二个参数为打开方式,常见的有:'r' ——只读,'w'——只写,文件长度将清0,'at'——读写打开一个文本文件,允许读或在文本末追加数据。函数返回指向该文件的指针。

2.读取字符串采用fgets()函数,第一个参数为数据缓冲区,第二个参数为读取字节长度,第三个参数为fopen返回的文件指针。注意该函数如果读到换行符或者EOF文件结束标识,则结束本次读操作。读入结束后,系统将自动在最后加'\0',并以数据缓冲区地址指针作为函数值返回。

3.字符串操作函数char *strrchr(char *str, char c);该函数的功能为:查找一个字符c在另一个字符串str中末次出现的位置(也就是从str的右侧开始查找字符c首次出现的位置),并返回从字符串中的这个位置起,一直到字符串结束的所有字符。如果未能找到指定字符,那么函数将返回NULL。

4.字符串操作函数char *strtok(char s[], const char *delim);功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。例如:strtok("abc,def,ghi",","),最后可以分割成为abc def ghi.尤其在点分十进制的IP中提取应用较多。在这里用来解析实例文本数据尤为方便。使用时要特别注意该函数的调用过程,第一次调用第一个参数需要设置被分割字符串,第二次及以后第一个参数设置成NULL。返回值指向分割后的子字符串。