如何从 char[][] 写入文件?
我将数据收集到 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
确保
fopen
返回的文件指针不为NULL;假设 arr 包含有效的以 0 结尾的字符串,这是我能想到的唯一会导致 fputs 呕吐的事情。Make sure the file pointer returned by
fopen
isn't NULL; assumingarr
contains valid 0-terminated strings, that's the only other thing I can think of that would causefputs
to barf.fputs
需要以\0
结尾的字符串。确保在您提供的字符串末尾添加0
。或者使用fwrite
。在
fopen
之后检查f != NULL
fputs
expects\0
-terminated string. Make sure you add0
in the end of the string that you supply there. Alternatively usefwrite
.check that
f != NULL
afterfopen
arr 指向什么?我猜问题是由于 arr 未初始化。
What is arr pointing to? I guess the problem is due to arr not being initialized.
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 declarearr
aschar arr[3][4];
and fill the last column with'\0'
(null) characters.也许您应该检查文件指针返回的值!
May be you should check for the value returned by the file pointer!