【问题标题】:Segmentation Fault when writing to a file in C在 C 中写入文件时出现分段错误
【发布时间】:2016-09-22 17:11:20
【问题描述】:

每当我尝试写入文件时,都会遇到分段错误。自从我在学校以来,我没有任何软件可以告诉我它来自哪里。如果有人可以帮助我,那就太好了。

//OLMHash.c

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

int main()
{
    createAccount();
    return 0;
}

struct account createAccount()
{


    struct account *newAccount;
    newAccount = (struct account *)malloc(sizeof(struct account));

    printf("Enter userid: ");
    scanf("%s", newAccount->userid);
    printf("\nEnter password: ");
    scanf("%s", newAccount->password);

    char *output = malloc(sizeof(char) * 255);
    strcpy(output, newAccount->userid);
    strcat(output, "\t");
    strcat(output, newAccount->password);

    FILE* fp;
    fp = fopen("accountslist.txt", "r");
    fputs(newAccount->userid, fp);

    free(output);
}

-

//OLMHash.h

struct account
{
    char userid[32];
    char password[12];  

};

struct account createAccount();

【问题讨论】:

  • 你的意见是什么?
  • 您打开文件是为了读取,而不是写入。请始终检查来自fopen()的返回值。
  • 我想我已经解决了。天气风向标是对的。当文件甚至还不存在时,我正在打开文件进行阅读。物理创建文件后,错误消失了。谢谢
  • 想想当用户输入 long 名称或密码时会发生什么...
  • 不使用为什么要分配output?为什么你的函数不返回它应该返回的东西?为什么编译时没有警告?

标签: c io segmentation-fault


【解决方案1】:

您打开文件是为了读取而不是写入,并且您没有检查操作是否成功。试试

fp = fopen("accountslist.txt", "w");
if(fp == NULL) {
    // get out code
    exit(1);
}

【讨论】:

    【解决方案2】:

    调用 fopen 时,我打开它是为了阅读而不是写作。我以物理方式创建了文件,因此我可以将其保留为“正在阅读”

    【讨论】:

    • 总是,总是,检查scanf 的返回。否则,您不知道您是在处理实际值还是垃圾。
    • 如果要写入文件,请打开文件进行写入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2018-08-06
    • 2021-06-14
    • 2012-01-03
    • 1970-01-01
    • 2022-10-04
    • 2019-03-27
    相关资源
    最近更新 更多