c - 为什么会发生分段错误(核心转储)
问题描述
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
FILE* fp;
FILE* ptr;
int cha, charac = 0, lines = 0, spaces = 0;
char ch;
fp = fopen("f.txt", "r");
while (ch != EOF) {
ch = fgetc(fp);
printf("%c", ch);
}
fclose(fp);
fp = fopen("fi.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2021);
fclose(fp);
if (fp == NULL)
printf("Can't Open File");
else {
while ((cha = fgetc(fp)) != EOF) {
charac++;
if (ch == ' ')
spaces++;
if (ch == '\n')
lines++;
}
fclose(fp);
printf("Character %d\n", charac);
printf("Spaces %d\n", spaces);
printf("Lines %d\n", lines);
}
}
解决方案
如果您尝试编写读取文件的代码,请计算行数/空格/字符并将其打印到屏幕上。然后编写另一个文件,其中包含“我们在 2021 年”。正确的?确定下面的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char * *argv, char * *envp) {
FILE *fRead;
FILE *fWrite;
int characters = 0, lines = 0, spaces = 0;
fRead = fopen("/Users/Shared/CommonAll/file1.txt", "r");
if (fRead == NULL) {
printf("ERROR: Could not open the SOURCE file!");
return (EXIT_FAILURE);
}
else {
char singleChar;
while(1){
singleChar = fgetc(fRead);
if(singleChar == EOF || (int)(singleChar) == -1){
break;
}
else if (singleChar == ' '){
spaces++;
}
else if ((int) (singleChar) == 13) {
lines++;
}
else {
characters++;
}
printf("%c", singleChar);
}
}
fclose(fRead);
fWrite = fopen("/Users/Shared/CommonAll/file2.txt", "w+");
if (fWrite == NULL) {
printf("ERROR: Could not open the TARGET file!");
return (EXIT_FAILURE);
}
fprintf(fWrite, "%s %s %s %d", "We", "are", "in", 2021);
fclose(fWrite);
printf("\nCharacter %d\n", characters);
printf("Spaces %d\n", spaces);
printf("Lines %d\n", lines);
return (EXIT_SUCCESS);
}
推荐阅读
- g++ - 为什么这个没有语法错误的嵌套类程序会产生垃圾输出,我该如何解决?
- javascript - 任何人都可以帮我使用 JQuery 对我的时间块进行颜色编码吗?
- php - 如何根据选定的时间创建 PHP 插入查询
- bash - bash 运行读取文件并运行读取行 OR 命令
- html - 如何从 HTML 中返回的 JSON 中获取值?
- javascript - 为什么我的 JSON 变量的值有“类型”和“数据”?
- regex - 如何使用 awk 检测嵌入的字段名称和重新排序字段?
- javascript - 如何在mounted() vuejs中销毁或阻止挂载事件
- flutter - Flutter - 插件如何保证安全和信任?
- python - 让 DataFrame 在定时持续时间内重复自身