[C语言]文件操作

C语言与文件操作 计算机中能在内存中存储数据,但是内存的大小为8~16G,这个大小如果被用完将会溢出数据,那么我们要怎么储存更大的数据呢?这就要将数据存储到硬盘中。如果要将数据存储到硬盘中,C语言提供了文件操作函数,可以把数据储存到文件中。这样就解决了内存不够大的问题。 阅读详情


为什么要使用文件操作?

当我们写出了通讯录时,我们会发现当退出重新打开程序后,通讯录并不会加载上一次退出前的信息,所有储存的信息全部会被销毁。我们想要给扫雷和三子棋等程序增加得分系统的时候也是这样,并不能保存用户的最高历史记录得分,而如何存储程序的信息到磁盘上,如何利用程序读取信息,就是文件操作的部分了。

文件名

一个文件要有一个唯一的文件标识,以便用户识别和引用。
文件名包含
3部分:文件路径+文件名主干+文件后缀 。
例如: c:\code\test.txt

文件的打开和关闭

缓冲文件系统中,关键的概念是“文件类型指针”,简称“文件指针”。
每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名字,文件状态及文件当前的位置等)。这些信息是保存在一个结构体变量中的。该结构体类型是由系统声明的,取名FILE。
FILE* pf;//文件指针变量
定义pf是一个指向FILE类型数据的指针变量。通过该文件信息区中的信息就能够访问该文件。也就是说通过文件指针变量能够找到与它关联的文件。

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。

//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream );

mode为打开文件的方式,打开文件的方式如下:


                       打开方式                  含义                                                  如果文件不存在 

r 只读  为了输出数据,打开一个已存在的文本文件 出错
w 只写  为了输出数据,打开一个文本文件创建新文件
a 追加  向文本文件尾部追加数据创建新文件
rb 只读
  为了输入数据,打开一个二进制文件
出错
wb 只写
  为了输出数据,打开一个二进制文件
创建新文件
ab 追加
  向一个二进制文件尾添加数据
出错
r+ 读写
  为了读和写,打开一个文本文件
出错
w+ 读写
  为了读和写,建议一个新的文件
创建新文件
a+ 读写
  打开一个文件,在文件尾进行读写
创建新文件
rb+ 读写
  为了读和写打开一个二进制文件
出错
wb+ 读写
  为了读和写,新建一个新的二进制文件
创建新文件
ab+ 读写
  打开一个二进制文件,在文件尾进行读和写
创建新文件

文件的读写

文件的读写有: fgetc, fputc, fgets, fputs, fscanf, fprintf 等适用于各种输入输出流的函数。

也有:fread, fwrite 这些适用于文件流的指令。

实例:

#include <stdio.h>
int main()
{
 int a = 10000;
 FILE* pf = fopen("test.txt", "wb");
 fwrite(&a, 4, 1, pf);//二进制的形式写到文件中
 fclose(pf);
 pf = NULL;
 return 0;
}
#include <stdio.h>
enum { SIZE = 5 };
int main(void)
{
    double a[SIZE] = {1.,2.,3.,4.,5.};
    FILE *fp = fopen("test.bin", "wb"); // 必须用二进制模式
    fwrite(a, sizeof *a, SIZE, fp); // 写 double 的数组
    fclose(fp);
    double b[SIZE];
    fp = fopen("test.bin","rb");
    size_t ret_code = fread(b, sizeof *b, SIZE, fp); // 读 double 的数组
    if(ret_code == SIZE) {
        puts("Array read successfully, contents: ");
        for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
        putchar('\n');
   } else { // error handling
       if (feof(fp))
          printf("Error reading test.bin: unexpected end of file\n");
       else if (ferror(fp)) {
           perror("Error reading test.bin");
       }
   }
    fclose(fp);
}

HAMi 核心模块与架构设计 HAMi 的架构设计是围绕 Kubernetes 生态系统构建的,通过扩展 Kubernetes 的调度能力和设备管理能力,为用户提供了高效、灵活的异构设备虚拟化和管理解决方案。 阅读详情

相关推荐

《遥感大模型生产级实战:从数据到决策的端到端AI工程》系列第一部分:AI遥感工程师的基础设施与工具链-文章 4:传统遥感分析与机器学习基线

本章将系统性地介绍经典遥感分析工作流,从数据预处理到多维度特征工程,再到如何利用经典的机器学习模型(如随机森林、支持向量机)进行监督与非监督学习。我们将通过一个完整的“智慧农业作物分类”项目实战,展示如何利用我们之前构建的数据湖和工具链,从原始数据到最终的分析结果,构建一个性能可靠、可解释性强的基线系统。更重要的是,我们将深入剖析这种传统方法的局限性,从而为后续章节引入遥感大模型的必要性提供强有力的论证。

panshengwu的博客 705

C语言实现的文件搜索和操作

#include &lt;stdio.h&gt; //该头文件的作用我就不说了,还不知道的打PP。#include &lt;io.h&gt; //我们需要的函数结构体和相应的函数功能就包含在内。 void main(){long i, j;struct _finddata_t ff; //查找文件的结构体变量,是_findfirst()和_findnext()的参数。char *dir = "....

mmdev 1908

搭建微信机器人的方案都在这了!

功能超级强大,虽不支持二次开发,但已有的功能足够个人使用,可惜官方作品已被腾讯告死,好在市面上还流落着不少破解版,有需要的自行搜索。可惜的是,微信官方已不准许新的微信号再使用 web 登录,这就直接从源头扼杀了 web 协议的微信机器人,虽说老的微信号还是能凑合着用,不过部分功能也受限。所以,这些都属于 PC 端的微信机器人。无论是 PC 端还是手机端,用 hook 方式实现的最大缺点就是要和某一个版本的微信客户端进行绑定,如果框架本身不对最新版本的微信适配,那使用的时候就无法升级到最新版本的微信。

weixin_47246330的博客 1万+

C语言基础⑩①——文件

文件是指存储在外存储器(即硬盘、U盘、闪盘、软盘等)上的数据的集合。

2401_82508270的博客 1215

从打印攻击到视频重放:手把手用OULU-NPU训练你的第一个活体检测模型

本文详细介绍了如何使用OULU-NPU数据集训练活体检测模型,以应对打印攻击和视频重放等安全威胁。通过PyTorch框架,从环境准备、数据加载、预处理到模型架构设计,手把手教你构建一个高效的双流网络,结合CNN和LSTM技术,提升模型在多种攻击场景下的检测准确率。

weixin_29092031的博客 385

【毕设级教程】从0到1实现基于YOLOv8的UA-DETRAC交通目标检测系统(含UI界面,助力智能交通毕设)

本项目基于YOLOv8模型和UA-DETRAC数据集开发了一个交通目标检测系统,包含数据处理、模型训练和可视化界面全流程。UA-DETRAC数据集包含多种交通场景下的车辆标注,通过格式转换适配YOLOv8训练要求。系统采用PyQt开发交互界面,支持图像检测、结果显示等功能。该项目技术路线清晰,既展现深度学习在智能交通中的应用,又提供完整的可视化展示方案,适合作为计算机视觉相关毕业设计选题。

m0_64661770的博客 150

c语言查找某路径下文件名中包含指定字符串的所有文件

#include &amp;lt;stdlib.h&amp;gt; #include &amp;lt;stdio.h&amp;gt; #include &amp;lt;unistd.h&amp;gt; #include &amp;lt;dirent.h&amp;gt; #include &amp;lt;string.h&amp;gt; #include &amp;lt;fcntl.h&amp;gt;

qq_42588901的博客 3761

【数据集】1980-2020年(5年)土地利用分类数据-中国科学院

简介1980-2020年每五年土地利用数据-中国科学院

WW、forever的博客 3932

C语言文件操作详解

如果你是一个C语言初学者,那么你一定发现,目前我们的C语言程序只会在执行后自动退出,而不会保存数据及运行结果,那么如何才能保存数据呢?为了保存数据,我们可以用到文件操作。

Eliauk_U的博客 2万+

材料仿真软件:Materials Studio_(14).电学性质计算

设置计算参数,包括 k 点网格、交换相关泛函等。

kkchenjj的博客 1863

一种基于机载LiDAR点云电力线自动提取方法

文章目录一、引言二、算法实现2.1实现步骤2.2实现代码 一、引言 二、算法实现 2.1实现步骤 (1)首先采用首先采用高程滤波方法去除地面点和低矮地物点,滤波后的点云数据中除电力线点云外还含部分杆塔点、高植被点和噪声点。 (2)根据点云空间维度特征提取电力线点,使用空间密度聚类的方法实现单根电力线精确分离。 2.2实现代码 在这里插入代码片 ...

dayuhaitang1的博客 5171

C语言常见文件操作函数总结详解

C语言文件操作函数,怕是很多人的痛,因为在各种地方都能用到,说的简单一点在某些课堂作业上,可能会让你去操作一个txt文档的读写,再就是课程设计时候老师要求把数据存放到文本文件中,我曾经见过一个粉丝问我问题,他们的老师要求简直离谱,是必须使用文本文档来存放数据!我直接就????????????,怎么还有这种要求阿?数据库操作也不是不行阿,非得用文本文件,虽说这样比较死板,但也侧面反映出了教学对文件操作的重视,再往深了说,比如你要解析某个文件格式,比如常见的PE文件,关于文件的读写几乎是必不可少的一步,首先得读

KOOKNUT的博客 2317

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

C语言文件操作

深入了解C语言文件操作及其相关函数实现。

南猿北者博客 1516

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C语言之文件操作

本文将全面详细的讲述C语言文件操作的基础知识,包括所右顺序读写的函数介绍以及随机读写的函数介绍,字数较多,感谢支持

x_p96484685433的博客 1381

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

c语言中的文件操作

引入: 磁盘上的文件都是文件。 对于日常生活中,我们在使用电子设备的时候,用到某个软件或者应用的时候,总是发现他们会在本地占用空间,即文件,是不是打开软件后,先前保留的数据都不见了呢?不是的,这些数据是被存放在文件里面的。 之前我们制作的动态储存版的通讯录(一个小项目,数据只能储存到内存中),程序是不是只要一关闭,保存的数据下次打开就消失了。这是因为没有将其数据保存在文件中,而是内存中,结束程序内存的空间也自然被释放,从而无法保留。 那么如果想要改进这个通讯录自然要加上文件操作的函数让其数据保留

QiHai的博客 6384

文件操作【C语言】

C语言还不会文件的一些操作?赶紧进来!!!

wzh18907434168的博客 1354

C语言文件操作总结

C语言文件操作 一、标准文件的读写 1.文件的打开 fopen() 文件的打开操作表示将给用户指定的文件在内存分配一个FILE结构区,并将该结构的指针返回给用户程序,以后用户程序就可用此FILE指针来实现对指定文件的存取操作了。当使用打开函数时,必须给出文件名、文件操作方式(读、写或读写),如果该文件名不存在,就意味着建立(只对写文件而言,对读文件则出错),并将文件指针指向文件开头。若已有一个同名...

Sock的博客 1088

C语言-文件操作函数大全

fopen` 函数用于打开一个文件,并返回一个指向该文件的指针。如果打开文件失败,`fopen` 会返回 `NULL`。```c```参数:- `path`: 要打开的文件的路径。- `mode`: 文件的打开模式(例如:`"r"` 读取模式,`"w"` 写入模式,`"a"` 追加模式等)。如果成功,返回一个指向 `FILE` 对象的指针。如果失败,返回 `NULL`。`fclose` 函数用于关闭由 `fopen` 函数打开的文件。

Jason_from_China的博客 2211
上一篇: [C语言]结构体大小计算——你的心到底够不够装下我
下一篇: [C语言实现]带你手撕带头循环双链表
FlashRider
博客等级 码龄4年 529粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值