一、实验目的
- 掌握串的实现;
- 掌握常用的C风格的串处理函数;
- 掌握文件的读写操作。
二、实验相关知识
- 复习C语言文件读写的相关知识
- 复习课本中第4章关于串的相关知识点;
三、实验内容与要求(二选一)
1.编程实现对指定文本文件进行查找与替换。
【设计要求】打开指定的文本文件inpaper.data,输入查找串t1和替换串t2,然后把inpaper.data文本文件中所有的t1串替换为t2串,并输出。
2.编写程序实现对0-1字符文件的压缩。
【设计要求】打开指定的文本文件source.data,该文件是用0和1字符所组成,把文件中每8个字符压缩成一个字节,若文件最后不足8位则以0补充,并写入输出文档out.data。
四、程序代码及运行结果
【程序代码】
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SOURCEFILE "inpaper.data"
#define MaxSize 100000
char inpaper[MaxSize];
char outpaper[MaxSize];
char t1[MaxSize]; //查找串
char t2[MaxSize]; //替换串
int Getdata(char paper[]);
void Replace(char Nstr[], char Cstr[], char t1[], char t2[]);
int Outputdata(char paper[]);
int main()
{
char *current;
int i = 0;
int j = 0;
Getdata(inpaper);
printf("%s", inpaper);
printf("请输入你要查找的串:\n");
gets(t1);
printf("请输入你替换后的串:\n");
gets(t2);
Replace(outpaper, inpaper, t1, t2);
Outputdata(outpaper);
printf("%s", outpaper);
}
int Getdata(char paper[])
{
FILE *fp;
if ((fp = fopen(SOURCEFILE, "rb")) == NULL) /* 以读方式打开文本文件 */
{
printf("Failure to open score.txt!\n");
return 0;//读数据失败
}
int i = 0;
while (!feof(fp))
{
fscanf(fp, "%c", &paper[i]);
i++;
}
fclose(fp);
return 1; //成功读数据
}
int Outputdata(char paper[])
{
FILE *fp;
if ((fp = fopen("out.data", "wb")) == NULL) /* 以写方式打开文本文件 */
{
printf("Failure to open score.txt!\n");
return 0;//写数据失败
}
for (int i = 0; paper[i] != '\n'; i++)
fprintf(fp, "%c", paper[i]);
fclose(fp);
return 1;
}
void Replace(char Nstr[], char Cstr[], char t1[], char t2[])
{
char *p = NULL;
char *pos = NULL;
pos = Cstr;
int len = strlen(t1);
while ((p = strstr(pos, t1)) != NULL)
{
strncpy(Nstr, pos, p - pos);
Nstr[p - pos] = '\0';
strcat(Nstr, t2);
strcat(Nstr, p + len);
strcpy(pos, Nstr);
}
strcpy(Nstr, pos);
}
【运行结果】



五、实验心得体会
巩固了字符串和文件读写的知识。

