在main函数中创建一个文件,将键盘输入的字符串(该字符串只包含字母和*)写入文件中。打开该文件,读出字符串。删除串中字母之间的*号,并将新串存放到另一个文件中。比如,字符串*a**B*cd**,删除字母之间的*号,得新串*aBcd**。
/* Note:Your choice is C IDE */
#include "stdio.h"
#include <stdlib.h>
void main()
{
FILE *fp;
char c;
char str[100]={'\0'};
char str1[100]={'\0'};
int i=0;
int j=0;
int k=0;
fp = fopen("d:\\test.txt","r");
c=fgetc(fp);
str[i++]=c;
while(c !=EOF){
c=fgetc(fp);
str[i++]=c;
}
//关闭
fclose(fp);
for(j=0;j<i;j++){
if(j==0 || j==i-2){
str1[k++] = str[j];
}else if(str[j]!='*'){
str1[k++]=str[j];
}
}
puts(str1);
//保存文件
if (!(fp = fopen("d:\\test.txt","w+")))
{
printf("test.txt打开失败\n");
return 0;
}
fwrite(str1,1,k,fp);
fclose(fp);
}
代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h>
#include <string>
int main()
{
char buf[1024] = {0};
FILE* fp;
printf("请输入字符串:\n");
gets(buf);
if ( !(fp = fopen("a.txt","w+")) )
{
printf("a.txt 打开失败\n");
return 0;
}
//写入文件
fwrite(buf,1,strlen(buf),fp);
fclose(fp);
fp = 0;
//读文件
if ( !(fp = fopen("a.txt","r+")))
{
printf("a.txt打开失败\n");
return 0;
}
//读取文件内容
fseek(fp,0,SEEK_END);
long lSize = ftell(fp);
char* text=new char[lSize+1];
rewind(fp);
lSize = fread(text,sizeof(char),lSize,fp);
text[lSize] = '\0';
fclose(fp);
fp = 0;
//删除字母之间的*
bool bgein = false;
char* tmp = new char[lSize +1];
int nmb = 0;
int start = 0;
int end = lSize-1;
//开始
for (; start < lSize; start++)
{
if(text[start] != '*')
break;
}
//结束
for (; end >= 0; end--)
{
if (text[end] != '*')
break;
}
//开始部分
for(int i = 0; i < start; i++)
{
tmp[nmb] = text[i];
nmb++;
}
//中间部分
for (int i = start; i <=end; i++)
{
if (text[i] != '*')
{
tmp[nmb] = text[i];
nmb++;
}
}
//最后部分
for (int i = end+1;i < lSize; i++)
{
tmp[nmb] = text[i];
nmb++;
}
//打开文件写入
if (!(fp = fopen("b.txt","w+")))
{
printf("b.txt打开失败\n");
return 0;
}
fwrite(tmp,1,nmb,fp);
fclose(fp);
delete[] text;
text = 0;
delete[] tmp;
tmp = 0;
//getchar();
//getchar();
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632