有些配置文件会以文件的形式存储。如何按行读出来呢? 当然存成xml格式是最好的。
介绍一个函数fgets, 估计是get string from file的缩写吧。这个函数在百度的百科里有详细介绍。摘录一下:
fgets 从文件结构体指针stream中读取数据,每次读取一行。读取的数据保存在buf指向的字符数组中,每次最多读取bufsize-1个字符(第
bufsize个字符赋'\0'),如果文件中的该行,不足bufsize个字符,则读完该行就结束。函数成功将返回buf,失败或读到文件结尾返回
NULL。因此我们不能直接通过fgets的返回值来判断函数是否是出错而终止的,应该借助feof函数或者ferror函数来判断。
函数原型:char *fgets(char *buf, int bufsize, FILE *stream);
参数:
*buf: 字符型指针,指向用来存储所得数据的地址。
bufsize: 整型数据,指明buf指向的字符数组的大小。
*stream: 文件结构体指针,将要读取的文件流。
-
#include <string.h>
-
#include <stdio.h>
-
int main(void)
-
{
-
FILE *stream;
-
char string[] = "This is a test";
-
char msg[20];
-
/* open a file for update */
-
stream = fopen("DUMMY.FIL", "w+");
-
/* write a string into the file */
-
fwrite(string, strlen(string), 1, stream);
-
/* seek to the start of the file */
-
fseek(stream, 0, SEEK_SET);
-
/* read a string from the file */
-
fgets(msg, strlen(string)+1, stream);
-
/* display the string */
-
printf("%s", msg);
-
fclose(stream);
-
return 0;
-
}
阅读(2879) | 评论(0) | 转发(0) |