本文实例为大家分享了C语言实现文件读写操作的具体代码,供大家参考,具体内容如下
键盘读入字符串写到文件中,再从文件读出显示在控制台
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#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); //系统自动打开stdout文件
}
fclose (fp);
}
|
合并两个文件的内容,并输出到第三个文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#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);
}
|
输入学生信息并转存到磁盘文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#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(); //转存
display();
}
void save()
{
FILE *fp;
int i;
if ((fp= fopen ( "E:\\计算机导论作业\\加密文档" , "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:\\计算机导论作业\\加密文档" , "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);
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_42316621/article/details/100065257