c - 长时间阅读后出现段错误

标签 c pointers struct scanf fgets

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

struct fileData
{
        char fileName[100];
        int size;
        char type;
        long timestamp;
};

void print(struct fileData *myFile);

int main(void)
{
        struct fileData *toUse = malloc(sizeof(toUse));
        char temp[100] = {0};

        printf("Enter the type:");
        getchar();
        scanf("%c", toUse->type);
        getchar();
        printf("Enter the filename:");
        fgets(temp, 100, stdin);
        strcpy(toUse->fileName, temp);
        printf("Enter the access time:");
        scanf("%lf", toUse->timestamp);
        printf("Enter the size:");
        scanf("%d", toUse->size);

        print(toUse);
        free(toUse);
}

void print(struct fileData *myFile)
{
        printf("Filename: %s - Size: %d - Type: [%c] - Accessed @ %ld\n", myFile->fileName, myFile->size, myFile->type, myFile->timestamp);
}

好的,下面是程序应该做的:

  1. 构造一个文件的数据结构(必须在main中使用一个指针)
  2. 结构的 malloc 内存,并提示/读入有关结构的数据
  3. 编写 1 个打印出该数据的函数

所以...上面是我的代码,我有几个问题:

  1. 您可能会注意到我在那里有一些 getchar(),这是因为无论出于何种原因,当我运行 ./a.out 时,它总是会跳过我猜测的第一个 scanf,因为当我按回车键它会卡在 stdin 中并将其解析为 scanf,因此将 getchar() 的工作放在一起......但是无论如何可以避免这种情况一起发生吗?这在我的任何其他程序中都从未发生过......

  2. 如您所见,我正在使用 fgets 获取字符串,因为文件名可能包含空格,而 scanf 无法处理空格。但我的问题是,我是否必须将其存储在临时文件中然后复制过来,或者我可以这样做: fgets(toUse->fileName, 100, stdin); 我假设不是,出于同样的原因我不能使用它: toUse->fileName = "测试"; 那么我目前的做法是否正确,还是有更好的方法?

  3. 现在对于导致我的程序失败的实际问题,下一篇阅读“输入访问时间:”,它会让我输入一个数字,但是当我按下回车键时,我得到了一个段错误..所以为什么?是因为我正在使用 %lf 吗?这是完全不同的东西吗?我应该只在 scanf 中使用 %l 吗? [当我这样做时,它会直接跳过问题..我假设出于同样的原因它会跳过其他问题..处理输入的东西]。这可能是我输入长“1234567890”后的回车导致它出现段错误还是我做错了什么?

任何问题的回答都会有所帮助,谢谢!

最佳答案

  1. 尝试 scanf("%c\n", ...) 以便 scanf 等待返回字符

  2. fgets(toUse->文件名, 100, 标准输入);可以工作,toUse->fileName = "Test";不要因为"Test"是指向"Test"字符串的指针,而toUse->fileName是一个缓冲区,可以直接fgets进去

  3. %lf 是长 float 格式。在你的 scanf 中尝试 %ld。然后你需要给 scanf 一个地址来写入,使用 scanf("%ld", &toUse->timestamp);

    大小相同:scanf("%d", toUse->size);应该是 scanf("%d", &toUse->size);

关于c - 长时间阅读后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120859/

相关文章:

java - Java 中的 For-Each 和指针

c - C 'deallocates' 局部堆栈变量时?

c++ - 在 C++ 程序中制作全局结构

c - 从 C 中的指针实例化一个新结构

C# 相当于 Python 的 struct.pack?

mysql - 当我尝试将我的变量插入我的数据库时,它被插入为零而不是预期值

c++ - c/c++编译器如何知道错误在哪一行

c - 节目结束前暂停

Swift UnsafeMutableRawPointer 返回类而不是实例

C - 数组不能使用变量作为索引