将结果传输到 txt 文件 C

Transfer results to txt file C

所以我对编程完全陌生(我已经学习了 3 天),我发现自己遇到了一个我根本不知道如何解决的问题。 我想让这个程序给我从 0 到 36 进制的特定数字的每个组合。当数字只有 50000 左右时,这很容易。但我的目标是提取实际的单词(也有数字),如果我尝试获取包含 5 个字符的单词,终端将开始覆盖之前的单词(没有帮助,我想要所有的单词)。 所以我想我应该寻找一种方法将所有内容都传输到一个 txt 文件中,但我的问题在于:我不知道如何...抱歉文本太长,但我想准确解释我想要得到的东西。感谢您的帮助。

int main() {
    int dec, j, i, q, r, k;
    char val[80];
    printf("Enter a decimal number: ");
    scanf("%d", &dec);
    for (k = 0; k <= dec; k++) { /*repeat for all possible combinations*/
        q = k;
        for (i = 1; q != 0; i++) { /*convert decimal number to value for base 36*/
            r = q % 36;
            if (r < 10)
                r = r + 48;
            else
                r = r + 55;
            val[i] = r;
            q = q / 36;
        }
        for (j = i - 1; j > 0; j--) { /*print every single value*/
            printf("%c", val[j]);
        }
        printf("    ");     /*add spaces because why not*/
    }
    return (0);
}

创建一个文件然后你可以使用 fprintf() 而不是 printf 两者之间的唯一区别是你需要将文件指定为参数

FILE *myFile = fopen("file.txt", "w"); //"w" erase previous content, "a" appends
If(myFile == NULL) {printf("Error in openning file\n"); exit(1);}  
fprintf(myFile, "some integer : %d\n", myInteger); // same as printf my specify file pointer name in first argument
fclose(myFile); //dont forget to close the file

一些可能有帮助的观察:

首先是 type 相关的: 在您的声明中创建以下内容:

int dec, j, i, q, r, k;
char val[80];

然后你再做作业:

val[i] = r;//assigning an int to a char, dangerous

虽然 r 是类型 intrange(通常)为 – 2,147,483,648 至 2,147,483,647,
val[i] 属于 char 类型,范围(通常)仅为 –128 到 127。

因此,您可能 运行 进入溢出,导致意外结果。 最直接的解决方案是对两个变量使用相同的类型。选择 intchar,但不能同时选择两者。

@Nasim 已经正确解决了另一个问题。使用 printf()file 版本 - fprintf()。正如 link 所示,fprintf() 的原型是:

int fprintf( FILE *stream, const char *format [, argument ]...);

用法示例:

FILE *fp = fopen(".\somefile.txt", "w");//create a pointer to a FILE
if(fp)//if the FILE was successfully created, write to it...
{
    // some of your previous code...
    for (j = i - 1; j > 0; j--) 
    { /*print every single value*/
            fprintf(fp, "%c", val[j]);//if val is typed as char
            //OR             
            fprintf(fp, "%d", val[j]);//if val is typed as int
    }
    fclose(fp);
}

最后,有多种方法可以执行碱基转换。有些more complicated than others.