鉴于某些txt文件很大,闲来无事,就变了一个简单的txt分割器,功能比较弱,用c写的,文件操作用得比较多
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
char *ReadData(FILE *fp,char *buf)
{
return fgets(buf,1024,fp);//读取一行到buf
}
main()
{
FILE *fp1,*fp2;
int i=0,j=0,length;
char name[50],*p,buf[1024],temp[50],c;
gets(temp);
length=strlen(temp);
gets(name);
fopen_s(&fp1,name,"r");//以只读方式读取文件
while(1)
{
if(i%500==0)//每500行分割一个文件
{
j++;
c=j+48;
temp[length]=c;
temp[length+1]='.';
temp[length+2]='t';
temp[length+3]='x';
temp[length+4]='t';
temp[length+5]='/0';
fopen_s(&fp2,temp,"w");
}
p=ReadData(fp1,buf);//读入一行
if(p==NULL)//读入失败,结束
break;
i++;
fputs(buf,fp2);//写入文件
}
}
其中一晚上都被fgets所困扰,后来在msdn中查到了一个示例函数,才解决了fgets的问题
#include <stdio.h>
int main( void )
{
FILE *stream;
char line[100];
int i;
if( fopen_s( &stream, "12.txt", "r" ) == 0 )
{
if( fgets( line, 100, stream ) == NULL)
printf( "fgets error/n" );
else
printf( "%s", line);
fclose( stream );
}
}
fopen_s是fopen的变种,比fopen更加安全,其中r代表以只读方式打开文件,w表示一直写方式打开文件,只写文件若不存在,则新建,文件结束,fgets()返回0,程序结束