DAY22 文件操作

知识点1【深拷贝】0-1在这里插入图片描述

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

typedef struct

{

	int num;

	char *name;

}DATA;

void test01()

{

	DATA data1;

	DATA data2;


	data1.num = 100;

	data1.name = (char *)calloc(1,12);

	strcpy(data1.name, "my data");


	data2.num = data1.num;

	//为结构体变量 申请 独立的空间

	data2.name = (char *)calloc(1,12);

	strcpy(data2.name, data1.name);


	printf("data1:num = %d, name=%s\n", data1.num, data1.name);

	printf("data2:num = %d, name=%s\n", data2.num, data2.name);


	if(data1.name != NULL)

	{

		free(data1.name);

		data1.name = NULL;

	}


	if(data2.name != NULL)

	{

		free(data2.name);

		data2.name = NULL;

	}



}

int main(int argc,char *argv[])

{

	test01();

	return 0;

}

运行结果
在这里插入图片描述总结:前提就是指针变量 作为 结构体的成员
浅拷贝:两个结构体变量 中的 指针成员 指向 同一块堆区空间。
深拷贝:两个结构体变量 中的 指针成员 指向 各自的堆区空间。
知识点2【文件】
在这里插入图片描述

//从文件中读取内容并输出到终端
#include <stdio.h>
#include <string.h>

extern void test01();
extern void test02();
int main (int argc,char *argv[])
{
	test02();
	return 0;
}

//字符的读写
void test01()
{
	FILE *fp1=NULL;
	FILE *fp2=NULL;
	char *path1="a.txt";
	char *path2="b.txt";

	//打开文件
	fp1=fopen(path1,"r");
	if(NULL==fp1)
	{
		perror("fopen");
		return ;
	}
	
	fp2=fopen(path2,"w");
	if(NULL==fp2)
	{
		perror("fopen");
		return ;
	}
	
	//读写操作
	while(1)
	{
		char ch;
		ch=fgetc(fp1);
		if(ch==EOF)
			break;
		fputc(ch,fp2);
	}

	//关闭文件
	fclose(fp1);
	fclose(fp2);

}

//字符串的读写
void test02()
{
	FILE *fp1=NULL;
	FILE *fp2=NULL;
	char *path1="c.txt";
	char *path2="d.txt";
	//打开两个文件让我康康
	fp1=fopen(path1,"r");
	if(NULL==fp1)
	{
		perror("fopen");	
		return;
	}
	fp2=fopen(path2,"w");
	if(NULL==fp2)
	{
		perror("fopen");
		return;
	}

	//读写操作呀
	while(1)
	{
		char str[128]="";
		char *ch=NULL;
		int n=sizeof(str)/sizeof(str[0]);
		ch=fgets(str,n,fp1);
		if(NULL==ch)//返回为空,怎退出(不是EOF)!!!
			break;
	//	printf("%s",ch);
		fputs(ch,fp2);

	}

	//兄弟,关掉文件
	fclose(fp1);
	fclose(fp2);
	
}
发布了6 篇原创文章 · 获赞 0 · 访问量 67

猜你喜欢

转载自blog.csdn.net/qq_42730522/article/details/104640486
今日推荐