c 程序在读取文件时终止

标签 c fgets terminate file-read fgetc

我正在尝试使用不同的函数从文本文件读取数据,例如 fgetc() , fgets()fscanf() 。在执行过程中,程序在读取 fgetc() 后终止。

#include <stdio.h>

void writeFile(FILE *, char *);
void readFile(FILE *,char *);

void main(void){
    FILE *file;
    char *path="temp/test.txt";
    printf("%s\n",path);
    writeFile(file,path);
    readFile(file,path);
    return;
}

void readFile(FILE *file, char *path){
    file = fopen(path , "r");
    if(file)
        printf("\n file opened");
    char *buff;

    char getc  = fgetc(file);
    printf("\n 1 char :: %c ",getc);

    getc  = fgetc(file);
    printf("\n 2 char :: %c ",getc);
    fgetc(file); 

    fgets(buff,25,file);
    printf("\n 3 gets :: %s ",buff);

    fgets(buff,255,file);
    printf("\n 4 gets :: %s ",buff);

    int fscan = fscanf(file,"%s", buff);
    printf("\n 5 fscan :: %s ",buff);

    int eof= fclose(file);
}

void writeFile(FILE *file, char *path){
    file = fopen(path , "w+");
    if(file)
        printf("\n file opened");
    char *fileStr= "this is not working";
    int putc = fputc('@',file);
    fputc('!',file);
    int puts = fputs("\nThis is test file.",file);
    int putf1 = fprintf(file, "\n Kinldy help to solve this");
    int putf2 = fprintf(file, "\n%s", fileStr);
    int eof= fclose(file);
}

注意:如果我评论writeFile(file,path);程序中的一行,它正确执行。

最佳答案

我对您的程序做了一些小更改,以便它读取文件并且不会收到警告。请尝试一下是否适合您。它现在不会终止,希望这会对您有所帮助。

#include <stdio.h>

void writeFile(FILE *, char *);

void readFile(FILE *, char *);

void main(void) {
    FILE *file = NULL;
    char *path = "temp/test.txt";
    printf("%s\n", path);
    writeFile(file, path);
    readFile(file, path);
    return;
}

void readFile(FILE *file, char *path) {
    file = fopen(path, "r");
    if (file)
        printf("\n file opened");
    char buff[255];

    int getc = fgetc(file);
    printf("\n 1 char :: %c ", getc);

    getc = fgetc(file);
    printf("\n 2 char :: %c ", getc);
    fgetc(file);

    fgets(buff, 25, file);
    printf("\n 3 gets :: %s ", buff);

    fgets(buff, 255, file);
    printf("\n 4 gets :: %s ", buff);

    int fscan = fscanf(file,"%254s", buff);
    printf("\n 5 fscan :: %s ", buff);

    int eof = fclose(file);
}

void writeFile(FILE *file, char *path) {
    file = fopen(path, "w+");
    if (file)
        printf("\n file opened");
    char *fileStr = "this is not working";
    int putc = fputc('@', file);
    fputc('!', file);
    int puts = fputs("\nThis is test file.", file);
    int putf1 = fprintf(file, "\n Kinldy help to solve this");
    int putf2 = fprintf(file, "\n%s", fileStr);
    int eof = fclose(file);
}

关于c 程序在读取文件时终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402654/

相关文章:

php - 使用php将文本变量从文本文件传递到html表单单元格

c - 指针运算

c - 在 MIPS 程序集中交换数组中的元素? (比较清楚的)

c - fputs 中的 fgets 给出段错误

php读写文件不保存前导空格

multithreading - 你如何杀死一个 core.async/thread?

c - 为什么我写的代码会出现段错误?

c - 使用 fget 时出现奇怪的情况

java - 单击 JFrame.EXIT_ON_CLOSE 时终止 while 循环

c - 如果不手动中断,无限循环何时终止?