2016-09-22 15 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

Cでのmallocのキャストは悪い考えです - http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc –

答えて

-2

のfopenを呼び出して、私は読んではなく、書き込みのためにそれを開きました。私は物理的に "読み込み"のままにしておくことができるようにファイルを作成しました

+0

常に、*常に*、 'scanf'の戻り値をチェックしてください。それ以外の場合は、実際の値やゴミを処理しているかどうかはわかりません。 –

+1

ファイルに書き込みたい場合は、書き込み用に開きます。 –

1

書き込みの代わりに読み込み用にファイルを開いたため、処理が正常に終了していません。お試しください

fp = fopen("accountslist.txt", "w"); 
if(fp == NULL) { 
    // get out code 
    exit(1); 
} 
関連する問題