存储文件名的字符串在 C 中发生了变化,我不知道为什么。认为它与 /0 字符有关

String storing filename is changed in C and I cannot figure out why. Think it's related to /0 character

我正在编写一个程序,要求我将随机数播种到 select 从 input_01.txt 到 input_10.txt 的文件中。每个输入文件的第一行都有一个 6 个字符的字母系列,我必须存储以备后用。出于某种原因,我从随机种子生成的 fname 在以下操作结束时附加了我从文件中读取的 6 个字符。我觉得这与 %s 寻找 \0 字符有关,但我不确定如何修复它:

void main()
{
    srand(time(NULL)); 
    int rng2 = 1; //(rand()%9)+1; seeding random number from 1 to 10 for input.txt set to 1 for testing, it won't generate 10 for some reason
    char rng2char[2];   
    sprintf(rng2char, "%d.txt", rng2);
    FILE *fileStream; 
    char letters [6];
    char fname[12] = "";
    printf("\nrng2 generated was %d",rng2);
    if (rng2==10)
        strcat(fname, "input_");
    else    
        strcat(fname, "input_0");
    strcat(fname, rng2char);
    printf("\nWe have chosen %s",fname);
    //below here fname is ruined
    fileStream = fopen (fname, "r");
    fgets (letters, 7, fileStream); 
    fclose(fileStream);
    //somewhere above here, fname is ruined
    printf("\nLETTERS ARE: %s",letters);

直到“此处下方”行,%s fname returns “input_01.txt” 符合预期。但是,之后它 returns "input_01.txtVHAGOI" 其中 VHAGOI 是 input.txt 的第一行 我是 C 语言的新手,非常感谢对我复杂代码的其他方面的任何和所有反馈,我愿意学习。感谢您的宝贵时间和帮助。

从 1 到 10 的播种随机数 input.txt 设置为 1 用于测试 ,由于某种原因它不会生成 10

    int rng2 = (rand()%9)+1; -> int rng2 = (rand()%10)+1;
    

计算您需要的字符数:

    char rng2char[2]; -> char rng2char[7];

我的决赛:

    #include <stddef.h>
    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    #include <stdlib.h>
    
    void main ()
    {
        // count your characters
        char rng2char[7];
        char letters[6];
        char fname[12] = "";
        int rng2;
        FILE * fileStream;

        srand (time (NULL));
        // mod 10 rather than 9
        rng2 = (rand () % 10) + 1;
    
        // no need for the if else
        sprintf (rng2char, "%d.txt", rng2);
        strcat (fname, "input_");
        strcat (fname, rng2char);
    
        fileStream = fopen (fname, "r");
        // check for successful open
        if ( fileStream != NULL)
        {
           fgets (letters, 7, fileStream);
           fclose (fileStream);
        }
        else
        {
            printf("fopen error");
        }
            // debug
            printf ("\nrng2 generated was %d", rng2);
            printf ("\nWe have chosen %s", fname);
            printf ("\nLETTERS ARE: %s", letters);
    }

我的输出,srand 10:

    rng2 generated was 10
    We have chosen input_10.txt
    LETTERS ARE: ABCDEF