1. 主页 > 世界杯新浪 >

C 语言中写入文件

C 语言中使用 fwrite 函数写入文件

C 语言中使用 write 函数写入文件

本文将演示关于如何在 C 语言中向文件写入的多种方法。

C 语言中使用 fwrite 函数写入文件

C 语言的标准 I/O 库提供了读/写文件的核心函数,即 fread 和 fwrite。fwrite 需要四个参数,一个 void 指针,表示数据应该从哪里获取,给定指针处数据元素的大小和数量,一个 FILE*指针,表示输出文件流。

需要注意的是,打开文件流应该先用 fopen 函数打开,该函数取所需模式的文件名并返回 FILE*。本例中,我们使用 w+ 模式打开文件进行读写。不过要注意,如果文件不存在,就会用给定的文件名创建一个新的文件。接下来,我们将检查返回的文件流指针是否有效。如果不是,就会打印相应的错误信息,并退出程序。一旦文件流指针得到验证,就可以调用 fwrite 函数。请记住,在程序退出之前应该用 fclose 函数关闭文件。

#include

#include

#include

const char* str = "Temporary string to be written to file!";

int main(void) {

const char* filename = "out.txt";

FILE* output_file = fopen(filename, "w+");

if (!output_file) {

perror("fopen");

exit(EXIT_FAILURE);

}

fwrite(str, 1, strlen(str), output_file);

printf("Done Writing!\n");

fclose(output_file);

exit(EXIT_SUCCESS);

}

C 语言中使用 write 函数写入文件

另外,我们也可以使用 write,这是一个符合 POSIX 标准的函数调用,它将给定的字节数写入文件描述符所引用的文件中。注意,文件描述符是一个与打开的文件流相关联的整数。为了检索描述符,我们应该用文件名路径调用 open 函数。write 函数以文件描述符为第一个参数,以 void*指向的数据缓冲区为第二个参数。第三个参数是要写入文件的字节数,在下面的例子中用 strlen 函数计算。

#include

#include

#include

#include

#include

const char* str = "Temporary string to be written to file!";

int main(void) {

const char* filename = "out.txt";

int fd = open(filename, O_WRONLY);

if (fd == -1) {

perror("open");

exit(EXIT_FAILURE);

}

write(fd, str, strlen(str));

printf("Done Writing!\n");

close(fd);

exit(EXIT_SUCCESS);

}

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe