1、创建一个文件并向其写入字符串
1 #include <stdio.h>
2
3 int main()
4 {
5 FILE *fp;
6 char str[] = "ddd\ndhdhd\ndshf\ndhf\nHello\nniaho f f\ndiof\nfdhiohf\nfhf\nff\njf\ nfjf\nfjf\new\nw\n";
7 fp = fopen("test.txt","w+");
8 fwrite(str, sizeof(str), 1, fp);
9 fclose(fp);
10
11 return 0 ;
12 }
2、读取文件的字符串并打印某一个子字符串
#include <stdio.h>
2 #include <string.h>
3 int main()
4 {
5 FILE *fp;
6 char *ret;
7 int count = 0;
8 fp = fopen("test.txt","r+");
9 char str[1000];
10 while(1)
11 {
12 fgets(str, sizeof(str), fp);
13 if(feof(fp))
14 {
15 break;
16 }
17 count++;
18 //每一次打印都是只打印一行
19 printf("%s",str);
20 }
21 //将文件test.txt中每一行字符串都写到str数组中
22 /*for(int i=0; i<count; i++)
23 {
24 fscanf(fp,"%s",&str[i]);
25 }
26 ret = strstr(str, "hello");
27 printf("子字符串是:%s", ret);
*/
29 //这里的str应该是文件中的最后一行字符串才对,可是打印出来却是空值
30 printf("dd %s",str);
31 return 0;
32
33 }
3、拷贝文件
1 #include <stdio.h>
2
3 int main()
4 {
5 FILE *fp1;
6 FILE *fp2;
7 char buf[1000];
8 fp1 = fopen("test.txt", "r+");
9 fp2 = fopen("test.log", "w+");
10 while(1)
11 {
12 fgets(buf, sizeof(buf), fp1);
13 if(feof(fp1))
14 {
15 break;
16 }
17 fputs(buf, fp2);
18 }
19
20 return 0 ;
21 }
4、打印文件里的内容到标准输出
1 #include <stdio.h>
2
3 int main()
4 {
5 FILE *fp;
6 char buf[1000];
7 fp = fopen("test.log", "r+");
8 while(1)
9 {
10 fgets(buf, sizeof(buf), fp);
11 if(feof(fp))
12 {
13 break;
14 }
15 printf("%s",buf);
16 }
17
18 return 0;
19 }
~