当前位置:网站首页>利用文件保存数据(c语言)
利用文件保存数据(c语言)
2022-04-23 05:48:00 【Chshyz】
将数据储存到本地文件
环境:CentOS7
后附常用文件操作函数和功能表
文件后缀
.doc(Word文件)、.txt(文本文件)、.dat(数据文件)、.c(C语言源程序文件)、.cpp(C++源程序文件)、.for(FORTRAN语言源程序文件)、.pas(Pascal语言源程序文件)、.obj(目标文件)、.exe(可执行文件)、.ppt(电子幻灯文件)、.bmp(图形文件)、.jpg(图像文件)。
文件类型
- 程序文件(可执行)
- 数据文件(ASCII文件和二进制文件)
①ASCII文件:文本文件,每一个字节存放一个字符ASCII代码(字符型、数值型)。
②二进制文件:把内存中的数据按原来的样子输出到磁盘上存储(数值型)。
例子:输入10000
ASCII形式输出到磁盘(5字节)
二进制形式输出到磁盘(2字节)
文件指针
每个使用过的文件都在内存中开辟出一个相应的文件信息区存放文件相关信息。这些信息存在一个结构体变量(FILE)中。
例:FILE * fp
打开和关闭文件
- 打开数据文件(fopen)
fopen (文件名,使用文件方式);
例:
FILE * fp; #定义一个文件指向变量fp
fp = fopen (“a”, “r”); #将fopen函数的返回值赋给fp - 关闭文件(fclose)
fclose (文件指针)
例:fclose (fp);
PS:
| 使用 | 意思 |
|---|---|
| r | 只读(ASCII文件) |
| w | 只写(ASCII文件) |
| a | 追加(向ASCII文件尾添加数据) |
| rb | 只读(二进制文件) |
| wb | 只写(二进制文件) |
| ab | 追加(向二进制文件尾添加数据) |
| r+ | 读写(打开一个ASCII文件读写) |
| w+ | 读写(建立一个新的ASCII文件) |
| a+ | 读写(ASCII文件) |
| rb+ | 读写(二进制文件) |
| wb+ | 读写(二进制文件) |
| ab+ | 读写(二进制文件) |
示例1:输入内容再送到磁盘
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE * fp;
char ch, filename[10];
printf ("请输入文件名:");
scanf ("%s", filename);
if ((fp = fopen (filename, "w")) == NULL) {
printf ("无法打开\n");
exit (0);
}
ch = getchar();
printf ("请输入内容,以#号结束:");
ch = getchar();
while (ch != '#') {
fputc (ch, fp);
putchar (ch);
ch = getchar ();
}
fclose (fp);
putchar (10);
return 0;
}
[root@chenshuyi c]# gcc -o fputc fputc.c
[root@chenshuyi c]# ./fputc
请输入文件名:one
请输入内容,以#号结束:happy every days!#
happy every days!
[root@chenshuyi c]# cat one
happy every days!

版权声明
本文为[Chshyz]所创,转载请带上原文链接,感谢
https://blog.csdn.net/HelloWorld_4396/article/details/120313726
边栏推荐
猜你喜欢

Robocode教程4——Robocode的游戏物理

Explanation of login page

The most practical chrome plug-in

P1586 solution to tetragonal theorem

C language file operation

1007 go running (hdu6808) in the fourth game of 2020 Hangzhou Electric Multi school competition

Kalman filter and inertial integrated navigation

Cf1427c the hard work of paparazzi

Installation and usage skills of idea

檢測技術與原理
随机推荐
队列解决约瑟夫问题
[leetcode 459] duplicate substring
ThreadLocal. Threadlocalmap analysis
[leetcode 350] intersection of two arrays II
Completely clean up MySQL win
Rainbow (DP)
Record the installation and configuration of gestermer on TX2, and then use GST RTSP server
Database - sorting data
SVN简单操作命令
SQL -- data definition
GDB debugger installation and use
Mysql database foundation
The most practical chrome plug-in
Usage scenario of copyonwritearraylist
1006 finding a mex (hdu6756)
Rust 中的 Rc智能指针
C#中?的这种形式
Cf1427c the hard work of paparazzi
Event listener
[leetcode 954] double pair array