首页 > 解决方案 > 为什么会发生分段错误(核心转储)

问题描述

#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);
    }
}

标签: csegmentation-fault

解决方案


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

推荐阅读