将 fwrite 与 char* 一起使用
Using fwrite with char*
如何使用 fwrite 写入带有 char* 的文件?如果我想将一个 char* 附加到一个文件的末尾,后面有一个换行符,这样的事情对吗?如果你有一个像这样的变量:
char* c = "some string";
会不会是:
FILE *fp = fopen("file.txt", "ab");
fwrite(c, sizeof(char*), sizeof(c), fp);
fwrite("\n", sizeof(char), 1, fp);
close(fp);
我对第二个 fwrite 语句有点困惑。是 sizeof(char*) 还是 sizeof(char)?我还应该有 sizeof(c) 还是不正确?任何建议将不胜感激,谢谢。
fwrite
的第一个调用是错误的。
fwrite(c, sizeof(char*), sizeof(c), fp);
应该这样写比如
fwrite(c, sizeof( char ), strlen( c ), fp);
即不包括其终止零字符的字符串文字"some string"
写入文件。
至于这次通话
fwrite("\n", sizeof(char), 1, fp);
然后一个字符'\n'
写入文件fp.
注意:字符串文字 "\n"
在内部表示为两个元素 { '\n', '[=18=]' }
.
的字符数组
函数声明为
size_t fwrite(const void * restrict ptr,
size_t size,
size_t nmemb,
FILE * restrict stream);
并根据 C 标准(7.21.8.2 fwrite 函数)
2 The fwrite function writes, from the array pointed to by ptr, up to
nmemb elements whose size is specified by size, to the stream pointed
to by stream. For each object, size calls are made to the fputc
function, taking the values (in order) from an array of unsigned char
exactly overlaying the object. The file position indicator for the
stream (if defined) is advanced by the number of characters
successfully written. If an error occurs, the resulting value of the
file position indicator for the stream is indeterminate.
这里的其他答案和评论会告诉您您发布的代码有什么问题,但更好的解决方案是使用 fputs
,它专门用于写出以 nul 结尾的字符串:
const char* c = "some string";
FILE *fp = fopen("file.txt", "ab");
fputs (c, fp);
fputs ("\n", fp);
fclose(fp);
如何使用 fwrite 写入带有 char* 的文件?如果我想将一个 char* 附加到一个文件的末尾,后面有一个换行符,这样的事情对吗?如果你有一个像这样的变量:
char* c = "some string";
会不会是:
FILE *fp = fopen("file.txt", "ab");
fwrite(c, sizeof(char*), sizeof(c), fp);
fwrite("\n", sizeof(char), 1, fp);
close(fp);
我对第二个 fwrite 语句有点困惑。是 sizeof(char*) 还是 sizeof(char)?我还应该有 sizeof(c) 还是不正确?任何建议将不胜感激,谢谢。
fwrite
的第一个调用是错误的。
fwrite(c, sizeof(char*), sizeof(c), fp);
应该这样写比如
fwrite(c, sizeof( char ), strlen( c ), fp);
即不包括其终止零字符的字符串文字"some string"
写入文件。
至于这次通话
fwrite("\n", sizeof(char), 1, fp);
然后一个字符'\n'
写入文件fp.
注意:字符串文字 "\n"
在内部表示为两个元素 { '\n', '[=18=]' }
.
函数声明为
size_t fwrite(const void * restrict ptr,
size_t size,
size_t nmemb,
FILE * restrict stream);
并根据 C 标准(7.21.8.2 fwrite 函数)
2 The fwrite function writes, from the array pointed to by ptr, up to nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls are made to the fputc function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.
这里的其他答案和评论会告诉您您发布的代码有什么问题,但更好的解决方案是使用 fputs
,它专门用于写出以 nul 结尾的字符串:
const char* c = "some string";
FILE *fp = fopen("file.txt", "ab");
fputs (c, fp);
fputs ("\n", fp);
fclose(fp);