代码如下
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#define FILEBUFFER_LENGTH 5000
#define EMPTY_STR "
//打开fileName指定的文件,从中读取第lineNumber行
//返回值:成功返回1,失败返回0
int get_file_line(char *result,char *fileName,int lineNumber)
{
FILE *filePointer;
int i=0;
char buffer[FILEBUFFER_LENGTH];
char *temp;
memset(buffer,' ',FILEBUFFER_LENGTH*sizeof(char));
strcpy(buffer,EMPTY_STR);
if((fileName==NULL)||(result==NULL))
{
return 0;
}
if(!(filePointer=fopen(fileName,"rb")))
{return 0;}
while((!feof(filePointer))&&(i<lineNumber))
{
if(!fgets(buffer,FILEBUFFER_LENGTH,filePointer))
{
return 0;
}
i++;//差点又忘记加这一句了
}
/* printf("
%d
",sizeof(*result));
if(strlen(buffer)>sizeof(*result))//不能够这么写,虽然fgets读取一行后会在末尾加上' ',但是sizeof(result)得到的结果却是result本身类型的大小,所以不能够这么算。当静态数组传入函数时,在函数内部只能知道它是一个指针
{
return 0;
}*/
if(0!=fclose(filePointer))
{
return 0;
}
if(0!=strcmp(buffer,EMPTY_STR))
{
while(NULL!=(temp=strstr(buffer,"
")))
{
*temp=' ';
}
while(NULL!=(temp=strstr(buffer,"
")))
{
*temp=' ';
}
strcpy(result,buffer);
}else
{
strcpy(result,EMPTY_STR);
return 0;
}
return 1;
}