2

如果某个程序有很多行代码将字符串打印到文件中,那么以下哪项是首选?我使用首选格式有多重要?

fprintf(file, "%s", "string to file");
fprintf(file, "string to file");
4

3 回答 3

4
fprintf(file, "%s", "string to file");
fprintf(file, "string to file");

If the string to be printed is variable in any way the former version is the preferred one, if the strings are constants, hard coded, then it is also save to use the latter.

The danger with using the latter version with variable strings is that an evil mind could enter conversion specifiers (%d, %s, ...) into the string which then would make the code pull something from the stack which was not meant to be pulled. This leads to mayor security issues.

于 2013-07-31T16:23:32.090 回答
4

如果您只打印一个字符串,您应该更喜欢使用fputs()

fputs("string to file", file);

它使用更少的开销,fprintf()因为它不进行格式化。它没有你展示的第二个版本的坑fprintf(),因为它没有%特殊处理。

于 2013-07-31T16:38:05.923 回答
0

我更喜欢没有任何格式的版本,比如

int fprint(FILE* file, char* s) {
  size_t ch_size = sizeof(char);
  size_t str_size = (strlen(s) + 1) * ch_size; 
  return fwrite(s , ch_size, str_size, file);
}

fprint(file, "string to file");
于 2013-08-21T14:57:12.533 回答