
正文
C语言基础文件读写操作
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
整理了一份C语言的文件读写件操作代码,测试时打开相应的注释即可。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h> /*
* EOF: 符号常量,其值为-1.
* fgets() 最多读取int-1个字符,遇换行或EOF即返回.
* fputs() 写文件时,忽略字符串截止符'\0'.
* fread()和fwrite() 数据块读写,多用于结构体数组(顺序存储的结构体).
*
* 函数原型:
* 读:
* int fgetc(FILE *stream);
* char *fgets(char *s, int size, FILE *stream);
* size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
* int fscanf(FILE *stream, const char *format, ...);
* 写:
* int fputc(int c, FILE *stream);
* int fputs(const char *s, FILE *stream);
* size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
* int fprintf(FILE *stream, const char *format, ...);
* 其他:
* void rewind(FILE *stream); 将文件内部的位置指针重新指向一个流(数据流/文件)的开头.
*
* 打开方式:
* r(read): 读
* w(write): 写
* a(append): 追加
* +: 读和写
* t(text): 文本文件,可省略不写
* b(banary): 二进制文件
*/ FILE *fp = NULL; // READ
void GetCharFromFile(FILE *fp)
{
int ch = ; while ((ch=fgetc(fp)) != EOF) //失败时返回 EOF
{
printf("fget: [%c]\n", ch);
}
} void GetLineFromFile(FILE *fp)
{
char line[] = ""; while (fgets(line, sizeof(line), fp) != NULL) //失败时返回 NULL
{
printf("fgets: [%s]\n", line);
}
} void GetBlockFromFile(FILE *fp)
{
int i = ;
int block[] = {};
int count = ; while (fread(block, sizeof(block), count, fp) == count) //失败时返回值 != count
{
printf("fread: ");
for (i=; i<; i++)
{
printf("%d ", block[i]);
}
printf("\n");
}
} void ReadFormatToFile(FILE *fp)
{
char file[] = "";
char func[] = "";
char date[] = "";
int line = ; fscanf(fp, "%s %s %d %[^\n]", file, func, &line, date); //返回读取元素个数,eg:4
printf("file: %s\n", file);
printf("func: %s\n", func);
printf("line: %d\n", line);
printf("date: %s\n", date);
} // WRITE
int WriteCharToFile(FILE *fp, char ch)
{
int ret = ; ret = fputc(ch,fp); //失败时返回EOF
return ret!=EOF?:-;
} int WriteStrToFile(FILE *fp, char *str)
{
int ret = ; ret = fputs(str, fp);
return ret!=EOF?:-; //失败时返回EOF
} int WriteBlockToFile(FILE *fp, const void *block, int size, int count)
{
int ret = ; ret = fwrite(block, size, count, fp); //失败时返回值 != count
return ret!=count?-:;
} int WriteFormatToFile(FILE *fp)
{
int ret = ; ret = fprintf(fp, "%s %s %d %s\n", __FILE__, __func__, __LINE__, __DATE__);
return ret<?-:; //失败时返回一个负值
} // MAIN
int main(int argc, char **argv)
{
char ch = 'r';
char *str = "Hello World.\n";
int block[] = {,,,,,,,,,};
char *filePath = "./ll"; fp = fopen(filePath, "w+"); //不关心文件存在与否,每次重写文件,并可读
if (NULL == fp)
{
perror("fopen");
return -;
} // WRITE
// printf("WriteCharToFile: %s\n", WriteCharToFile(fp, ch)?"Fail":"Success");
printf("WriteStrToFile: %s\n", WriteStrToFile(fp, str)?"Fail":"Success");
// printf("WriteBlockToFile: %s\n", WriteBlockToFile(fp, block, sizeof(block), 1)?"Fail":"Success");
// printf("WriteFormatToFile: %s\n", WriteFormatToFile(fp)?"Fail":"Success"); rewind(fp);
// READ
// GetCharFromFile(fp);
GetLineFromFile(fp);
// GetBlockFromFile(fp);
// ReadFormatToFile(fp); fclose(fp);
return ;
}








