如何在 C 中使用文件 IO

Tags
C语言
IO
ID
39
 
  1. 打开文件:fopen
  1. 读取文件:fscanf 或者 fgets
  1. 写入文件:fprintf 或者 fputs
  1. 关闭文件:fclose
  1. 定位在文件中的位置:fseek
示例代码:
#include <stdio.h> int main() { FILE *file; char buffer[100]; // 打开文件,如果文件不存在,则创建一个新的文件 file = fopen("example.txt", "w+"); if (file == NULL) { printf("Error opening the file.\n"); return 1; } // 写入数据到文件 fprintf(file, "Hello, world!\n"); fprintf(file, "This is a file I/O example.\n"); // 回到文件起始位置 fseek(file, 0, SEEK_SET); // 读取文件内容并打印 while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("%s", buffer); } // 关闭文件 fclose(file); return 0; }