使用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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM