C语言如何将文件中一行内容按照空格分割,并将每个单词写入数组?
1个回答
展开全部
程序已调试过,运行的时候把filename改为你自己路径下的文件。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[1000];
void openfile(char *filename)
{
FILE *fp;
int file_size;
if((fp=fopen(filename,"r")) == NULL)
{
printf("can not open this file\n");
exit(0);
}
fseek(fp,0,SEEK_END);
file_size=ftell(fp);
printf("%d\n",file_size);
fseek(fp,0,SEEK_SET);
fread(str,sizeof(char),file_size,fp);
str[file_size-1]='\0';
printf("%s\n",str);
fclose(fp);
}
void Split()
{
char w[100][100];
char *pfirst=str;
char *pend;
int i=0;
int j,sum=0;
memset(w,0,sizeof(w));
while(pfirst)
{
pend=strstr(pfirst," ");
if(pend==NULL)
{
strncpy(w[i],pfirst,strlen(str)-sum);
i++;
break;
}
strncpy(w[i],pfirst,pend-pfirst);
sum+=pend-pfirst+1;
pfirst=++pend;
i++;
}
for(j=0;j<i;j++)
printf("%s ",w[j]);
}
int main()
{
char filename[40]="/opt/opthb/liuly/a.txt";
openfile(filename);
Split();
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[1000];
void openfile(char *filename)
{
FILE *fp;
int file_size;
if((fp=fopen(filename,"r")) == NULL)
{
printf("can not open this file\n");
exit(0);
}
fseek(fp,0,SEEK_END);
file_size=ftell(fp);
printf("%d\n",file_size);
fseek(fp,0,SEEK_SET);
fread(str,sizeof(char),file_size,fp);
str[file_size-1]='\0';
printf("%s\n",str);
fclose(fp);
}
void Split()
{
char w[100][100];
char *pfirst=str;
char *pend;
int i=0;
int j,sum=0;
memset(w,0,sizeof(w));
while(pfirst)
{
pend=strstr(pfirst," ");
if(pend==NULL)
{
strncpy(w[i],pfirst,strlen(str)-sum);
i++;
break;
}
strncpy(w[i],pfirst,pend-pfirst);
sum+=pend-pfirst+1;
pfirst=++pend;
i++;
}
for(j=0;j<i;j++)
printf("%s ",w[j]);
}
int main()
{
char filename[40]="/opt/opthb/liuly/a.txt";
openfile(filename);
Split();
return 0;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |