如何从 char[][] 写入文件?

发布于 2024-12-02 07:54:05 字数 292 浏览 1 评论 0原文

我将数据收集到 char[][] 数组中,然后让用户选择将哪个字符串写入文件。所以我

char arr[3][3]; // assume there are three different two-char long strings in there
FILE* f = fopen("file", "w");
fputs(arr[1], f);
fclose(f);

现在的问题是,我在 fputs() 调用上遇到了段错误,但我不知道为什么。

有什么想法吗?

I am gathering data into a char[][] array, then let a user choose which of those string to write to a file. So I'm doing for example

char arr[3][3]; // assume there are three different two-char long strings in there
FILE* f = fopen("file", "w");
fputs(arr[1], f);
fclose(f);

Now the problem is, I'm getting a segfault on the fputs() call and I dont know why.

Any Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

初雪 2024-12-09 07:54:05

确保fopen返回的文件指针不为NULL;假设 arr 包含有效的以 0 结尾的字符串,这是我能想到的唯一会导致 fputs 呕吐的事情。

Make sure the file pointer returned by fopen isn't NULL; assuming arr contains valid 0-terminated strings, that's the only other thing I can think of that would cause fputs to barf.

追星践月 2024-12-09 07:54:05
  1. fputs 需要以 \0 结尾的字符串。确保在您提供的字符串末尾添加 0。或者使用 fwrite

  2. fopen之后检查f != NULL

  1. fputs expects \0-terminated string. Make sure you add 0 in the end of the string that you supply there. Alternatively use fwrite.

  2. check that f != NULL after fopen

仙女山的月亮 2024-12-09 07:54:05

arr 指向什么?我猜问题是由于 arr 未初始化。

What is arr pointing to? I guess the problem is due to arr not being initialized.

紫轩蝶泪 2024-12-09 07:54:05

arr[1] 指向的 char 数组可能不是以 null 终止的。您应该将 arr 声明为 char arr[3][4]; 并用 '\0' (空)字符填充最后一列。

The char array pointed to by arr[1] is probably not null-terminated. You should declare arr as char arr[3][4]; and fill the last column with '\0' (null) characters.

水溶 2024-12-09 07:54:05

也许您应该检查文件指针返回的值!

May be you should check for the value returned by the file pointer!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文