【问题标题】:Why is Segmentation fault (core dumped) occurring为什么会发生分段错误(核心转储)
【发布时间】:2021-12-04 04:46:31
【问题描述】:
#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);
    }
}

【问题讨论】:

  • 几乎可以肯定不是 sigsegv 的情况,但 cha=fgetc(fp)if(ch == ' ') 看起来很奇怪,但如果没有完整的程序,就不可能完全确定您要做什么。
  • @Aaqib 将变量 cha 声明为 int 类型。 int cha;
  • @VladfromMoscow 还是一样的错误
  • @IanBush 我已经上传了完整的代码首先我读了一个文件然后我用“w+”打开了一个文件来写东西然后试图找出总行数和字符数跨度>
  • @Aaqib 需要检查文件是否打开成功即fp不等于NULL。

标签: c segmentation-fault


【解决方案1】:

如果您尝试编写读取文件的代码,请计算行数/空格/字符并将其打印到屏幕上。然后编写另一个文件,其中包含“我们在 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);
}

【讨论】:

  • 如果你要在运行语句中添加return(),如果if (fRead == NULL) 为真,则不需要else
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 2015-05-23
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多