【问题标题】:Checking size of string before operation with fscanf?在使用 fscanf 操作之前检查字符串的大小?
【发布时间】:2013-03-25 18:05:03
【问题描述】:

我正在尝试编写一个安全的文件输入。我有一个 128 的固定缓冲区大小。我想从文件中读取字符串,但在复制它们之前,我想检查它们的长度是否小于或等于 128

我可以这样做吗:

fscanf(fp, "%128s", myString)

我已经看到以相同方式使用的 scanf 会限制读取的字符数,但没有看到任何对它的引用以这种方式与 fscanf 和字符串一起使用?

【问题讨论】:

  • 我不明白这个问题。问题中的代码有什么问题?
  • cplusplus.com/reference/cstdio/fscanf 宽度在参考文献中有所提及。
  • 基本上所有scanf 都可以,fscanf 可以。
  • @LightnessRacesinOrbit 你在说什么? Those listed here are supported by the latest C下次检查你批评的链接。
  • @Armin:更喜欢权威的 C 参考。众所周知,cplusplus.com 对 C++ 不准确,我不敢想它对 C 的覆盖程度如何

标签: c


【解决方案1】:

是的,你可以这样做,但你落后 1 分。 所以如果你有一个长度为 128 个字符的数组:

char myString[128] = {'\0'};
fscanf(fp, %127s", myString);

您提到您已经看到scanf() 中使用的语法,这与以下内容相同:

fscanf(stdin, "%127s", myString); // just like scanf("%127s", myString);

注意man pagescanf()fscanf() 的格式字符串有关的信息是如何相同的

【讨论】:

    【解决方案2】:

    您可以使用char * fgets ( char * str, int num, FILE * stream ); 来避免缓冲区溢出

    喜欢:

    fgets(myString, 127, fp);
    

    【讨论】:

    • 减一。对于 128 个字符的缓冲区,可以有 127 个字符和 '\0'。调用 fgets(myString, 128, fp) 会读取 127 个字符并附加 '\0'。 The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.tutorialspoint.com/cprogramming/c_file_io.htm
    【解决方案3】:

    如果你在 windows 平台上,我认为你可以使用fscanf_s,否则我认为最好使用fgets 和/或sscanf :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 2016-09-14
      • 2018-07-01
      • 2018-02-16
      相关资源
      最近更新 更多