写入 txt 文件的数据以某种奇怪的语言出现 [C]

地平线

因此,我编写了一个程序,该程序将接收有关 DVD 的信息(特别是它的位置IDkey(只是一些随机数)标题流派发行年份,并使用结构将这些信息写入 .txt名为“person.txt”的文件我很肯定我的代码大部分都可以工作,但是当我去测试它时,.txt 文件中收到的输出是用某种奇怪的符号语言而不是英语编写的,坦率地说,我不知道为什么会这样。任何关于为什么会发生这种情况的解释将不胜感激,谢谢:)

程序

#include <stdio.h>
#include <stdlib.h>

// a struct to read and write
struct dvd
{
    int fposition;
    int fIdKey;
    char ftitle[50];
    char fgenre[50];
    int fyear;
};

int main ()
{
    FILE *outfile;
    struct dvd input;

    // open file for writing
    outfile = fopen ("person.txt", "w");
    if (outfile == NULL)
    {
        fprintf(stderr, "\nError opend file\n");
        exit (1);
    }


    printf("Postion: ");
    scanf("%d", &input.fposition);

    printf("ID Key: ");
    scanf("%d", &input.fIdKey);

    printf("Title: ");
    scanf("%s",&input.ftitle);

    printf("Genre: ");
    scanf("%s", &input.fgenre);

    printf("Year: ");
    scanf("%d", &input.fyear);

    // write struct to file
    fwrite (&input, sizeof(struct dvd), 1, outfile);

    if(fwrite != 0)
        printf("contents to file written successfully !\n");
    else
        printf("error writing file !\n");

    // close file
    fclose (outfile);

    return 0;
}

试运行

.TXT 文件中的测试运行输出

约翰·兹温克

您正在将这些值写入文件:

int fposition;
int fIdKey;
char ftitle[50];
char fgenre[50];
int fyear;

But you are displaying the whole file as characters. That kind of works for ftitle and fgenre because they really are characters...though since you don't populate all 50 characters there are some ugly uninitialized characters shown as well. That is easy to fix: just fill the unused characters (as well as the null terminator) with some known character (such as space) before writing to the file, or do not write the unused characters at all. You can use strlen() to find the length of each string and memset() to set the unused characters to a well-known character which is printable.

Next, saving an int and reading it as text is problematic. You need to decide on a single format. Either you write as integers like now, and you read as integers (which means you need a special program to read the file), or you commit to writing only text to the file.

Easiest might be to only write text to the file. You can use fprintf() for that, instead of fwrite(). You can use fprintf() for the character arrays as well, it will automatically write only the "used" part of each string up to the null terminator, skipping all the "garbage" characters.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章