2016-09-22 35 views
-2

每当我尝试写入文件时,出现分段错误。我没有任何软件可以告诉我自从我上学以后它来自哪里。如果任何人都可以帮助我,那会很棒。写入C文件时出现分段错误

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

您的输入是什么? –

+5

您打开文件进行阅读而不是写作。并请*总是*检查'fopen()'的返回值。 –

+0

Cast for malloc in C is a bad idea - http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc –

回答

-2

当调用的fopen,我打开它读取,而不是写。我物理创建文件的方式,我可以把它留作“阅读”

+0

总是,* always *,检查scanf的返回值。否则,你不知道你是否正在处理实际值或垃圾。 –

+1

如果要写入文件,请将其打开以进行写入。 –

1

您打开文件进行阅读而不是写作,并且您没有检查成功的操作。尝试

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