2015-10-14 247 views
0

我在讀取C文件時遇到問題。
我想逐行讀取文件。
每行包含25個字符,每個字符都有一個特殊值,我必須在其他函數中使用它。我的代碼:逐行讀取文件,逐字符C

int read_file(const char* filename){ 

    FILE* file = fopen(filename, "r"); 
    char line[25]; 
    int i; 
    int counter = 0; 



    while (fgets(line, sizeof(line), file)) 
    { 
     if (counter == 0) 
     { 
      counter++; 
     } 
     else 
     { 

       for(i = 0; i < 25 ; i++){ 
        printf("%s",line[i]); 
       } 
     } 
    } 

    fclose(file); 

    return 0; 
} 

我必須做別的事情,然後打印出來,但是當我嘗試這個代碼,它給了錯誤,所以做其他事情也會做同樣的我猜。 所以我的代碼需要逐行讀取文件,然後我需要能夠逐字讀取它。

+2

檢查'fopen()函數'第一返回值。 –

+0

這一行:'char line [25];'不夠大,不能輸入25個char字符。它需要更多空間用於換行符,而更多空間用於尾隨的NUL字節。 – user3629249

回答

2
  • 25個元素的數組不足以存儲25個字符的行:換行符爲+1,終止空字符爲+1。
  • 您應該檢查文件的開頭是否成功
  • %c必須用於通過printf打印一個字符。

固定代碼:

#include <stdio.h> 

int read_file(const char* filename){ 

    FILE* file = fopen(filename, "r"); 
    char line[27]; /* an array of 25 elements isn't enough to store lines of 25 characters: +1 for newline and +1 for terminating null character */ 
    int i; 
    int counter = 0; 

    if (file == NULL) return 1; /* check if the file is successfully opened */ 

    while (fgets(line, sizeof(line), file)) 
    { 
     if (counter == 0) 
     { 
      counter++; 
     } 
     else 
     { 

      for(i = 0; i < 25 ; i++){ 
       printf("%c",line[i]); /* use %c instead of %s to print one character */ 
      } 
     } 
    } 

    fclose(file); 

    return 0; 
} 
1
printf("%s",line[i]);  // %s expects char * and line[i] is a char 

這應該是 -

printf("%c",line[i]);  // to print character by charcter 

要存儲25字符聲明line爲 -

char line[25+1]; // +1 for null character 

- 當您在留言問%s可以作爲 -

printf("%s",line);   // no loop required 
+0

你什麼時候使用%s? – fangio

+0

'%s'可用於打印** sttring **。例如:'printf(「%s」,行);' – MikeCAT

+0

@fangio當你想打印** C風格的字符串**。 C風格的字符串是_null終止字符array_。 – ameyCU