C語言實現(xiàn)文件讀寫操作
更新時間:2020年12月28日 10:33:23 作者:零商
這篇文章主要為大家詳細介紹了C語言實現(xiàn)文件讀寫操作,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)文件讀寫操作的具體代碼,供大家參考,具體內(nèi)容如下
鍵盤讀入字符串寫到文件中,再從文件讀出顯示在控制臺
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char string[6];//方括號中是幾就輸入幾個字符串
if( (fp=fopen("file.txt","w"))==NULL )
{
printf("cannot open file");
return 0;
}
while(strlen(gets(string)) > 0)
{
fputs(string,fp);
fputs("\n",fp);
}
fclose(fp);
if( (fp=fopen("file.txt","r"))==NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(string,6,fp)!=NULL)
{
fputs(string,stdout);//系統(tǒng)自動打開stdout文件
}
fclose(fp);
}
合并兩個文件的內(nèi)容,并輸出到第三個文件
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char str1[10],str2[10];
printf("輸入兩串字母\n");
scanf("%s",str1);
scanf("%s",str2);
//A,B兩個文件賦值
if((fp1=fopen("A.txt","w"))==NULL)
{
printf("cannot open file\n");
return 0;
}
fputs(str1,fp1);
fclose(fp1);
if((fp2=fopen("B.txt","w"))==NULL)
{
printf("cannot open file\n");
return 0;
}
fputs(str2,fp2);
fclose(fp2);
//拷貝到第三個文件
if((fp1=fopen("A.txt","r"))==NULL)
{
printf("cannot open file\n");
return 0;
}
if((fp2=fopen("B.txt","r"))==NULL)
{
printf("cannot open file\n");
return 0;
}
if((fp3=fopen("C.txt","a"))==NULL)
{
printf("cannot open file\n");
return 0;
}
while(!feof(fp1))
{
fputc(fgetc(fp1),fp3);
}
while(!feof(fp2))
{
fputc(fgetc(fp2),fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
輸入學生信息并轉(zhuǎn)存到磁盤文件
#include<stdio.h>
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
char addr[15];
};
struct student_type stud[SIZE];
void save();
void display();
void main()
{
int i;
for(i=0;i<SIZE;i++)
{
scanf("%s %d %d %s",stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
}
save();//轉(zhuǎn)存
display();
}
void save()
{
FILE *fp;
int i;
if((fp=fopen("E:\\計算機導論作業(yè)\\加密文檔","wb"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stud[i], sizeof(struct student_type),1,fp)!=1)
printf("file write error\n");
}
fclose(fp);
}
void display()
{
FILE *fp;
int i;
if((fp=fopen("E:\\計算機導論作業(yè)\\加密文檔","rb"))==NULL)
{
printf("cannot open file\n");
return;
}
for(i=0;i<SIZE;i++)
{
fread(&stud[i], sizeof(struct student_type), 1, fp);
printf("%-10s %4d %4d %-15s\n",stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
}
fclose(fp);
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++實現(xiàn)關(guān)系與關(guān)系矩陣的代碼詳解
這篇文章主要介紹了C++實現(xiàn)關(guān)系與關(guān)系矩陣,功能實現(xiàn)包括關(guān)系的矩陣表示,關(guān)系的性質(zhì)判斷及關(guān)系的合成,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04

