这代码哪不对,dq函数运行出错,main函数就没错
c4droid吧
全部回复
仅看楼主
level 8
梦想家275 楼主
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<malloc.h>
int dq (void);
int dq(void) {
char b[1];
FILE *fp;
fp = fopen("/mnt/sdcard/1c/math.txt", "w");
if (fp == NULL)
printf("打开文件失败");
char a;
int i = 0;
while (a != '#') {
i++;
a = getche();
fprintf(fp, "%c", a);
}
fclose(fp);
char *str = (char *)malloc(sizeof(char) * i);
*str = NULL;
fp = fopen("/mnt/sdcard/1c/math.txt", "r+");
if (fp == NULL)
printf("打开文件失败");
a = 'q';
for (int p = 0; p < i - 1; p++) {
b[0]=(char)fgetc(fp);
strcat(str, b);
}
printf("\n输入的是:%s", str);
fclose(fp);
return 0;
}
int main(void){
dq();
return 0;
}
2016年07月07日 14点07分 1
level 8
梦想家275 楼主
这是运行结果
jskfhsbxk#
输入的是:Segmentation fault
2016年07月07日 14点07分 2
level 8
梦想家275 楼主
如果代码放在main函数里运行后是
hsjsbafo#
输入的是:hsjsbafo
2016年07月07日 14点07分 3
第二次打开文件不要+,因为这样会导致文件指针被移到结尾,所以读不了
2016年07月07日 15点07分
@不知者来此 :
#include<stdio.h> #
include
#include<conio.h> #
include #include int dq(void); int dq(void) { char
2016年07月07日 15点07分
@不知者来此 这样也不行
2016年07月07日 15点07分
level 14
我觉得文件打开失败之后应该立即返回,而不是打个字符串后继续错误的执行
2016年07月07日 14点07分 4
嗯,对[啊]
2016年07月07日 15点07分
可是,,如题的原因是啥
2016年07月07日 15点07分
level 8
梦想家275 楼主
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<malloc.h>
int dq(void);
int dq(void) {
char b[1];
FILE *fp;
fp = fopen("/mnt/sdcard/1c/math.txt", "w");
if (fp == NULL) {
printf("打开文件失败");
return 0;
}
char a;
int i = 0;
while (a != '#') {
i++;
a = getche();
fprintf(fp, "%c", a);
}
fclose(fp);
char *str = (char *)malloc(sizeof(char) * i);
*str = NULL;
fp = fopen("/mnt/sdcard/1c/math.txt", "r");
if (fp == NULL) {
printf("打开文件失败");
return 0;
}
a = 'q';
for (int p = 0; p < i - 1; p++) {
b[0] = (char)fgetc(fp);
strcat(str, b);
}
printf("\n输入的是:%s", str);
fclose(fp);
return 0;
}
int main(void) {
dq();
return 0;
}
这样也不行啊
2016年07月07日 15点07分 5
b的长度应该是2并且b[1]为0
2016年07月07日 15点07分
@不知者来此 好了[哈哈]谢谢了,哈哈
2016年07月07日 15点07分
@不知者来此 但为什么直接在main函数里可以运行
2016年07月07日 15点07分
回复 梦想家275 :这个我就不解释了,跟内存分配机制有关。
2016年07月07日 15点07分
1