c - 用 C 写入文件时出现段错误

标签 c io segmentation-fault

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

//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();

最佳答案

您打开文件进行读取而不是写入,并且您没有检查操作是否成功。尝试一下

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

关于c - 用 C 写入文件时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645056/

相关文章:

c - 零元素数组需要什么?

c# - 异步读取/写入同一流?

c - 使用 SQLite3 和 C 的段错误

函数末尾的 C++ 段错误。引用线 = 右大括号

c - 用 C 模糊图像

c - 在冒泡排序中得到错误的输出

io - 如何从 Rust 中的文件或标准输入执行多态 IO?

C pthread 段错误

c - 如何在 qt creator 中为 gcc 添加选项?

sockets - Haskell中的套接字编程: putStrLn/hPutStrLn not behaving as expected [duplicate]