开发者

How to write to file from char[][]?

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 开发者_如何学Pythonare 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?


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.


  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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜