本文实例为大家分享了C语言按行读写文件的具体代码,供大家参考,具体内容如下
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void my_fputs(char* path)
{
FILE* fp = NULL;
//"w+",读写方式打开,如果文件不存在,则创建\
如果文件存在,清空内容,再写
fp = fopen(path, "w+");
if (fp == NULL)
{
//函数参数只能是字符串
perror("my_fputs fopen");
return;
}
//写文件
char* buf[] = { "this ", "is a test \n", "for fputs" };
int i = 0, n = sizeof(buf)/sizeof(buf[0]);
for (i = 0; i < n; i++)
{
//返回值,成功,和失败,成功是0,失败非0
int len = fputs(buf[i], fp);
printf("len = %d\n", len);
}
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
}
void my_fgets(char* path)
{
FILE* fp = NULL;
//读写方式打开,如果文件不存在,打开失败
fp = fopen(path, "r+");
if (fp == NULL)
{
perror("my_fgets fopen");
return;
}
char buf[100];//char buf[100] = { 0 };
while (!feof(fp))//文件没有结束
{
//sizeof(buf),最大值,放不下只能放100;如果不超过100,按实际大小存放
//返回值,成功读取文件内容
//会把“\n”读取,以“\n”作为换行的标志
//fgets()读取完毕后,自动加字符串结束符0
char* p = fgets(buf, sizeof(buf), fp);
if (p != NULL)
{
printf("buf = %s\n", buf);
printf("%s\n", p);
}
}
printf("\n");
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
}
int main(void)
{
my_fputs("../003.txt");//上一级地址
my_fgets("../003.txt");
printf("\n");
system("pause");
return 0;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)