综合描述按字符,按行,按块读写方式。
#include <stdio.h>
#include <string.h>
void fileCharWrite() {
FILE *file_write = fopen("./test01.txt", "w");
if (!file_write) {
perror("ERROR");
return;
}
char ch = 'a';
for (int i = 0; i < 5; ++i) {
fputc(ch, file_write);
}
fclose(file_write);
}
void fileCharRead() {
FILE *file_read = fopen("./test01.txt", "r");
if (!file_read) {
perror("ERROR");
return;
}
char ch;
while ((ch = fgetc(file_read)) != EOF) {
printf("%c\n", ch);
}
fclose(file_read);
}
void fileLineReadWrite() {
FILE *file_write = fopen("./test02.txt", "w");
if (!file_write) {
perror("ERROR");
return;
}
char *arr[] = {
"锄禾日当午\n",
"汗滴禾下土\n",
"谁知盘中餐\n",
"粒粒皆辛苦\n"
};
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
fputs(arr[i], file_write);
}
fclose(file_write);
FILE *file_read = fopen("./test02.txt", "r");
if (!file_read) {
perror("ERROR");
return;
}
char temp[100] = {0};
while (fgets(temp, 100, file_read)) {
printf("%s", temp);
}
fclose(file_read);
}
void fileBlockReadWrite() {
FILE *file = fopen("./test03.txt", "w");
if (!file) {
perror("ERROR");
return;
}
char *arr[] = {
"锄禾日当午\n",
"汗滴禾下土\n",
"谁知盘中餐\n",
"粒粒皆辛苦\n"
};
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
fwrite(arr[i], strlen(arr[i]), 1, file);
}
fclose(file);
file = fopen("./test03.txt", "r");
if (!file) {
perror("ERROR");
return;
}
char temp[100] = {0};
while (fread(temp, strlen(arr[0]), 1, file)) {
printf("%s", temp);
}
fclose(file);
}
void test() {
fileBlockReadWrite();
}
int main(int argc, char const *argv[]) {
test();
return 0;
}