C语言实现数据写入文件

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

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

  1. fopen函数

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

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

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

r只读
w写入
r+读写
w+写入、更新
  1. 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<stdio.h>
#include <conio.h>
#include <stdlib.h>
#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");
}

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

  • 61
    点赞
  • 290
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值