【问题标题】:Troubles appending structure to file in C在 C 中将结构附加到文件时出现问题
【发布时间】:2014-10-22 13:39:06
【问题描述】:

我在将结构附加到文件时遇到了一些麻烦: 操作系统:Ubuntu 14.04

结构:

struct baris
{
    char name[30];
    char trusted[1];
    int phone;
    int id;
};

功能:

addNewBariga()
{
    char answer[30];
    struct baris new;
    while(1){
        printf("Enter new Barigas' ID please.");
        scanf("%d",&new.id);
        printf("Enter new Barigas' name please.\n");
        scanf("%s",new.name);
        printf("Enter new Barigas phone please. \n");
        scanf("%d", &new.phone);
        printf("Is Bariga trusted?\n\t[Y/N]:");
        scanf("%s",new.trusted);
        while(1)
        {
            if(strcmp(new.trusted,"Y") != 0 && strcmp(new.trusted,"y")  != 0)
            {
                printf("%s",new.trusted);
                printf("\nWrong command givven.\t\n[Y/N]:");
                scanf("%s",&new.trusted);
            }
            else
                break;
        }
        printf("Values you've entered:\n\tID:%d\n\tName: %s\n\tPhone: %d\n\tTrustworth:%s\nWould you like to proceed to saving?\n[Y/N]:\n",new.id,new.name,new.phone,new.trusted);
        scanf("%s",&answer);
        if(strcmp(answer,"Y") ==0 || strcmp(answer,"y")==0) //Process to saving
        {
            printf("saving...");
            confPtr = fopen(filePath , "ab");
            //fwrite(new.id, sizeof(new.id), 1, confPtr);
            fwrite(&new, sizeof(struct baris), 1, confPtr);
            fclose(confPtr);
            break;
        }
}

我得到了什么:

fabio\00\00\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00 <1\B5y\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00 \C5f\DAy\00\00\00\00\00\00\00

【问题讨论】:

  • 欢迎来到 Stack Overflow! “代码片段”仅适用于 Javascript/HTML,不适用于“任何”代码。 (由于没有那么详细的工具提示,这实际上是一个容易犯的错误。)
  • @Jongware 是的,我看到我刚刚添加它是为了突出显示,还有其他方法吗?
  • char trusted[1]; 的意义是什么?为什么不char trusted;%c
  • scanf("%s",new.trusted); trusted 是一个字符。 char trusted[1]; 应该是 char trusted[2];
  • “我得到了什么”??????你到底是从哪里得到的?您没有在您提供的代码中的任何地方读取文件。

标签: c file io structure fwrite


【解决方案1】:

这个输出看起来基本正确,你期待什么?

您正在将二进制数据写入二进制文件。二进制文件不是很容易手动检查。

例如,结构的第一个成员 name 在输出中总是 30 字节长。

请注意@BLUEPIXY 在评论中指出:

scanf("%s",new.trusted);

如果输入非零长度,则触发未定义的行为,因为trusted 仅是字符串终止符使用的 1 个字符长。您应该增加它的长度,或者(更好!)像这样停止使用直接scanf(),而是使用fgets() 读取整行输入并使用sscanf() 解析它。

此外,当使用可能失败的函数(如 scanf()sscanf()fgets())时,您必须在依赖返回值成功之前检查它们。

【讨论】:

  • printf 上的输出似乎没问题。我会检查一下长度和fgets。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
相关资源
最近更新 更多