2014-01-21 4 views
0

그래서 내가하려고하는 것은 공백 행을 계산하는 것입니다. 이는 공백뿐만 아니라 '\ n'그러나 스페이스와 탭 기호도 포함한다는 것을 의미합니다. 어떤 도움을 주셔서 감사합니다! :)C에서 파일의 빈 줄을 계산하는 방법은 무엇입니까?

char line[300]; 
int emptyline = 0; 
FILE *fp; 
fp = fopen("test.txt", "r"); 
if(fp == NULL) 
{ 
    perror("Error while opening the file. \n"); 
    system("pause"); 
} 
else 
{ 
    while (fgets(line, sizeof line, fp)) 
    { 
     int i = 0; 
     if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') 
     { 
      i++; 
     } 
     emptyline++; 
    } 
    printf("\n The number of empty lines is: %d\n", emptyline); 
} 
fclose(fp); 
+0

매뉴얼 페이지를 읽지 않는 이유 - http://www.cplusplus.com/reference/cstdio/fgets/ -'fgets'는 한 줄을 읽습니다. 비어 있는지 확인해야합니다. –

+0

else 블록을 사용하여'emptyline ++'을'continue' 또는'wrapped해야합니다 – Billie

답변

0

회선 루프에 들어가기 전에 emptyLine 카운터를 증가시키고 공백 문자가 아닌 문자가 감소하는 경우 emptyLine 카운터가 루프를 중단합니다.

#include <stdio.h> 
#include <string.h> 

int getEmptyLines(const char *fileName) 
{ 
    char line[300]; 
    int emptyLine = 0; 
    FILE *fp = fopen("text.txt", "r"); 
    if (fp == NULL) { 
     printf("Error: Could not open specified file!\n"); 
     return -1; 
    } 
    else { 
     while(fgets(line, 300, fp)) { 
      int i = 0; 
      int len = strlen(line); 
      emptyLine++; 
      for (i = 0; i < len; i++) { 
       if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') { 
        emptyLine--; 
        break; 
       } 
      } 
     } 
     return emptyLine; 
    } 
} 

int main(void) 
{ 
    const char fileName[] = "text.txt"; 
    int emptyLines = getEmptyLines(fileName); 
    if (emptyLines >= 0) { 
     printf("The number of empty lines is %d", emptyLines); 
    } 
    return 0; 
} 
1

SO에 게시 할 때 코드를 올바르게 입력해야합니다. 과 emptyline이 모두 증가하지만 printf()으로 전화하면 el을 사용합니다. 그리고 코드가 }ine 인 곳에서 무엇이 있어야하는지 모르겠습니다. 제발, 적어도 노력하십시오.

처음에는 모든 행에 대해 if 문 외부에 있기 때문에 emptyline이 증가합니다.

둘째, 공백 문자가 아닌 문자가 포함되어 있는지 전체 행을 테스트해야합니다. 그것이 사실 일 경우에만 emptyline을 증가시켜야합니다.

int IsEmptyLine(char *line) 
{ 
    while (*line) 
    { 
     if (!isspace(*line++)) 
      return 0; 
    } 
    return 1; 
} 
0

당신은 모든 반복에 emptyline를 증가, 그래서 당신은 else 블록에 포장해야한다.

0

이 문제를 논리적으로 생각해보고 기능을 사용하여 무슨 일이 일어나는지 명확히 설명해 보겠습니다.

먼저 공백으로 만 이루어진 행을 검색하려고합니다. 그럼 그렇게 할 함수를 만들어 봅시다.

bool StringIsOnlyWhitespace(const char * line) { 
    int i; 
    for (i=0; line[i] != '\0'; ++i) 
     if (!isspace(line[i])) 
      return false; 
    return true; 
} 

이제 테스트 함수가 생겼으니 루프를 만들어 보겠습니다. fgets() 적어도 sizeof(line) 문자가 라인 전체 라인 (그것의 한 부분)을 반환하지 않습니다

while (fgets(line, sizeof line, fp)) { 
    if (StringIsOnlyWhitespace(line)) 
     emptyline++; 
} 

printf("\n The number of empty lines is: %d\n", emptyline); 

참고.

관련 문제