zoukankan      html  css  js  c++  java
  • 4.10文件的读写

    Q 创建一个后缀名为txt的文件,并向该文件写入一个字符串保存起来。再打开该文件,读出文件中的内容。

    注意:所有的I/O函数都定义在 #include<stdio.h> 或者#include"stdio.h"

    常用I/O函数:

    FILE *fopen(char *filename,char *type);		//打开指定路径的文件 
    int fclose(FILE *fp);			    //关闭文件 
    int fread(void *buf,int size,int count,FILE *fp); //读文件函数 
    int fwrite(void *buf,int size,int count,FILE *fp);//写文件函数 
    

      

    完整程序:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
    	FILE *fp;//fp是一个FILE类型变量,用来保存一个文件指针 
    	char pathName[20],txt1[20]={''},txt2[20]{''}; //pathName是字符型的数组首地址,用来保存文件路径
    	//txt1用来保存输入的字符串,txt2用来保存从文件中读出的字符串,赋值{''},因为这是C中默认的字符串结束标志 
    	int fileLen;	//用来存储输入的字符串长度 
    	printf("type the path name of the file
    ");
    	scanf("%s",pathName);
    	
    	fp=fopen(pathName,"w");//以写的方式打开文件 
    	printf("input a string to this file
    ");
    	scanf("%s",txt1);		//将字符串写入文件 
    	fileLen=strlen(txt1);
    	fwrite(txt1,fileLen,1,fp);	//将字符串内容写入文件 
    	fclose(fp);				//关闭文件
    	 
    	printf("the file has been saved
    ");
    	printf("the cintent of the file: %s is 
    ",pathName);
    	fp=fopen(pathName,"r");//以读的方式打开文件 
    	fread(txt2,fileLen,1,fp);//将文件内容读入缓冲区txt2 
    	printf("%s
    ",txt2);	//将字符串输出到屏幕上 
    	getchar();
    
    	return 0;
    }
    

      

    疑惑:发现在下面的语句中不需要&,也可以运行,这是什么情况???

    scanf("%s",pathName);

    scanf("%s",txt1);

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    ASP.NET页面打印技术的总结
    js传递中文参数的url到asp(jscript)解释得到的中文参数为乱码的解决方法
    header的用法(PHP)
    oracle 11g road(/dev/shm需注意)
    mysql 主从同步 Error 'Out of range value for column的问题
    linux shell 过滤特殊字符开始的行
    Oracle穿越incarnation恢复数据
    多普达A6388刷机2.3
    【忽悠普通人用】隐藏文件夹的方法
    电脑同时使用双网卡实现方法
  • 原文地址:https://www.cnblogs.com/dd2hm/p/6755922.html
Copyright © 2011-2022 走看看