使用c语言向本地文件写入数据的一个实现

一、写个编程脚本

#include <stdio.h>
//author: Simon
 
int writeInfoToFile(char *strFile)
{
	int i;
	char name[20];
	FILE *fp;
	fp = fopen(strFile, "w");
	if(fp == NULL)
	{
		perror("fopen");
		return -1;
	}
	printf("Note: please input three time names,every name's length less than 20 character\n");
	for(i=0; i<3; i++)
	{
		if(i==2){
			printf("Now,Open another terminal and change the name of the document to other\n");
			printf("input the third name:\n");
                	scanf("%s", name);
                	fprintf(fp, "%s\n", name);
			break;
		}
		printf("input name:\n");
		scanf("%s", name);
		fprintf(fp, "%s\n", name);
	}

	fclose(fp);
	
}

int main()
{
	char file[20] = "data.txt";
	writeInfoToFile(file);
}

现在我们保存成test.c文件编译一下并验证

gcc test.c
./a.out                                                                      #按照提示执行即可

二、现在我们来做个小实验

这个c语言编程程序中,我们是先打开一个文件,fopen表示打开文件操作。然后我们按照执行的流程写入数据:一共手动写三次数据,在写第三次数据之前我们把这个data.txt文件给重命名一下,然后再来看还能不能写入数据了,以及写入的数据在哪个文件中。
执行一下,

[root@master2 ~]# ./a.out 
Note: please input three time names,every name's length less than 20 character
input name:
zhoujielun
input name:
zhangyimou
Now,Open another terminal and change the name of the document to other
input the third name:                                                                                                 # 暂时不输入数据。

现在我们先不输入数据,我们打开另外一个终端,然后把data.txt文件重命名一下

[root@master2 ~]# mv data.txt data.txt.bak
anaconda-ks.cfg  a.out  data.txt.bak  init.sh  test.c

现在我们继续回到第一个终端,把第三个名字写一下,写完之后我们查看一下data.txt.bak文件

[root@master2 ~]# ls
anaconda-ks.cfg  a.out  data.txt.bak  init.sh  test.c
[root@master2 ~]# cat data.txt.bak 
zhoujielun
zhangyimou
zhanghan

可以看到对于一个已经打开的文件,重命名该文件依然可以写入数据,是不会丢失的。linux文件系统中,改名并不会影响已经打开文件的写入操作,内核inode不变,

当然,我对脚本也进行了进一步的优化,可以看看下面这个

#include <stdio.h>
//author: Simon
 
int writeInfoToFile(char *strFile)
{
	int i;
	char name[20];
	FILE *fp;
	printf("Note: please input three time names,every name's length less than 20 character\n");
	for(i=0; i<3; i++)
	{
		if(i==2){
			fp = fopen(strFile, "a+");
			printf("Now,Open another terminal and change the name of the document to other\n");
			printf("input the third name:\n");
                	scanf("%s", name);
                	fprintf(fp, "%s\n", name);
			fclose(fp);
			break;
		}
		printf("input name:\n");
		scanf("%s", name);
		fp = fopen(strFile, "a+");
		fprintf(fp, "%s\n", name);
		fclose(fp);
	}

	
}

int main()
{
	char file[20] = "data.txt";
	writeInfoToFile(file);
}
posted @ 2020-08-20 16:54  峰哥ge  阅读(2240)  评论(0编辑  收藏  举报