【问题标题】:can i store 'mode' in a variable and use it at fopen()我可以将 \'mode\' 存储在变量中并在 fopen() 中使用它吗
【发布时间】:2022-11-30 16:17:04
【问题描述】:
char mode;

printf("---------------------------------------")
scanf(" %c", mode);
FILE * fpointer = fopen("kkkkkkkk.txt", mode);`

我试过但没有结果。编译器没有给我错误,但没有让程序完全运行。

【问题讨论】:

  • 你得到什么意想不到的行为?请包括预期行为和实际行为,包括任何错误的全文。
  • 可以,但是模式是细绳(即指向以零结尾的 char 缓冲区的指针),而不是 char。
  • 请记住,您通过了细绳对于 fopen 模式,不是单个 char 值。还请记住,scanf 的 %c 格式需要一个指针到 char 变量。
  • 并且编译器至少应该警告您 fopen 的错误参数。编译器还能够捕获 scanf 参数中的不匹配,但您可能需要为此启用更多警告(这通常是个好主意)。

标签: c


【解决方案1】:

欢迎来到堆栈溢出。

fopen(3) 的第二个参数应该是 const char * 类型(本质上是一个字符串)。但是,您使用了一个 char,但它不起作用。另外,我不认为你已经初始化了它。这是一个工作示例。

#include <stdio.h>

int main(void) {
  char mode[5];
  scanf("%s", mode);
  printf("Received mode is '%s'
", mode);
  FILE *fp = fopen("sample.txt", mode);
  if (fp == NULL) {
    perror("Couldn't open file ");
  } else {
    printf("Done! Closing
");
    fclose(fp);
  }
}

这里有两个运行来指示发生了什么。

ن ./sample
r
Received mode is 'r'
Couldn't open file : No such file or directory

在此处以"r" 模式打开它。由于sample.txt 不存在,我们得到一个错误。

ن ./sample
w
Received mode is 'w'
Done! Closing

ن ./sample
r
Received mode is 'r'
Done! Closing

第一次,它以"w" 模式打开并创建它。下一次,"r" 将工作,因为 sample.txt 文件存在。

【讨论】:

  • 你没有回答问题。 OP想根据scanf的结果动态改变模式
  • @mousetail 我是在强调问题而不是提供完整的解决方案,但我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 2017-08-14
  • 2022-08-18
  • 2023-02-06
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
相关资源
最近更新 更多