【问题标题】:How to write something in a existing .txt file with c program?如何使用 c 程序在现有的 .txt 文件中写入内容?
【发布时间】:2021-05-06 05:13:38
【问题描述】:

我正在尝试使用 C 程序在现有的 test.txt 文件中写入“文件已打开”。但是我不能用该程序创建一个 test.txt 文件。我必须在现有文件中写入。

我试过了,但做不到。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000] = "File opened";
    fopen("test.txt", "w");
    fprintf("%s", sentence);
    fclose();
    return 0;
}

显示的错误是:

error: too few arguments to function 'fclose'

我该怎么做?请帮帮我。

【问题讨论】:

  • 另外,如果你想追加到现有文件,你需要"a" 而不是"w"。如果你想覆盖现有文件,那么"w" 就可以了。

标签: c file


【解决方案1】:

以后建议您搜索人们提出的现有问题或进行一些研究。即查找 fopen 的手册或规范:https://man7.org/linux/man-pages/man3/fopen.3.html

特别是因为您的代码没有编译,因为它有错误,fopen、fprintf 和 fclose 所有缺少参数或赋值变量。阅读这些错误和编译器消息将引导您找到解决方案。这是固定的和使用“w+”选项的样子:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000] = "File opened";
    FILE *file = fopen("test.txt", "w+");
    fprintf( file, "%s", sentence);
    fclose( file );
    return 0;
}

如果您想了解更多,这是一个很好的教程:https://www.geeksforgeeks.org/basics-file-handling-c/

【讨论】:

  • 它创建了一个 test.txt 文件,但我想编写一个现有的 test.txt 文件。
  • 您阅读以上链接了吗? fopen 的手册页会告诉您根据您的需要更改什么.....即“w+”“a”甚至“a+”??
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 2010-10-09
  • 2017-06-09
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多