【发布时间】: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