C语言实现数据写入文件 您所在的位置:网站首页 c语言fopen_s打开文件写入 C语言实现数据写入文件

C语言实现数据写入文件

2024-06-20 17:33| 来源: 网络整理| 查看: 265

向文件中写入数据(C语言)

在分析数据时,首先要解决数据的保存问题,c中提供了相应的函数来实现将数据写入指定文件中的功能

fopen函数

使用 fopen( ) 函数来创建一个新的文件或者打开一个已有的文件

FILE *fopen(const chat *filename,const char *mode)

传入参数:filename为文件名,mode为打开方式,控制读写权限,数据形式为字符串。 常用模式如下:

r只读w写入r+读写w+写入、更新 fputs函数

fputs()函数根据指定的格式,向输出流(stream)写入数据

int fputs(const char *str, FILE *stream)

传入参数:其中 stream为指向FILE对象的指针,str:这是一个数组,包含了要写入的以空字符终止的字符序列

/** * C program to create a file and write data into file. */ #include #include #include #define DATA_SIZE 200 void ExpDataWrite() { /* Variable to store user content */ char data[DATA_SIZE]; const char* filename = "F:/X.txt"; %设置文件放置位置 /* File pointer to hold reference to our file */ FILE* fptr = fopen(filename , "w");%fptr为文件指针,可通过fptr来实现对 文件的操作 /* fopen() return NULL if last operation was unsuccessful */ if (fp1 == NULL)%若打开文件失败,fopen会返回NULL { puts("Fail to open file!"); exit(1); } /* Input contents from user to store in file */ printf("Enter contents to store in file : \n"); fgets(data, DATA_SIZE, stdin); /* Write data to file */ fputs(data, fPtr); /* Close file to save file data */ fclose(fptr); /* Success message */ printf("Data saved successfully.\n"); }

注意:在设置文件存放位置时路径中用 ‘/’



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有