2016-09-09 45 views
-1

我試圖從文本文件中讀取數據,使用不同的功能,如fgetc(),fgets()fscanf()。在執行過程中,從fgetc()讀取後終止。c程序從文件中讀取時終止

#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);行,它會正確執行。

+4

'字符* BUFF;' - >'字符的buff [255];' – BLUEPIXY

+0

如果聲明'和'255'字符buff',你也應該設置'的fscanf(文件 「%254S」, buff);'以保證你不會溢出(如果你碰巧有一個不會中斷的字符序列,不會超過'buff'的大小 - 不太可能,但爲了防止未定義的行爲,你應該) –

回答

-1

我對程序做了一些小的修改,以便它讀取文件並且不會收到警告。請嘗試,如果它適合你。它不會終止,希望這會幫助你。

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