2017-02-18 179 views
0

我试图使此代码为了从文件中读取希腊字母并打印使用fscanf发声的英文字母。问题是我不断收到分段错误。我错过了什么?使用fscanf分段错误 - 不分配内存问题

#include <stdio.h> 

int main() 
{    
    char s[100];  
    int i; 
    FILE * myfile; 

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r"); 

    while(fscanf(myfile, "%s", s) == 1) 
     { 
      for (i=0 ; i<100 ; i++) 
       { 
        if (s[i] == 'Α') 
         { printf("A") ; } 
        else 
        if (s[i] == 'Β') 
         { printf("V") ; } 
     } 
} 
+2

步骤1:'的fscanf(MYFILE, “%s” 时,S)' - >'的fscanf(MYFILE, “%99S”,S)',以防止缓存器溢出。 – chux

+1

不要访问传递读取的数据。 (for =(i = 0; i <100; i ++)' - >'for(i = 0; s [i]; i ++)'。需要查看哪些输入用于诊断分段故障。同时测试'myfile == NULL'。 – chux

+2

检查'fopen'的返回值。 – BLUEPIXY

回答

1

您的代码有3个严重问题。

1)您从不检查fopen是否成功。

2)您可能会读取未初始化的签名数据。

3)你可能会溢出在输入缓冲区

所有三件事情可能会导致程序失败。

尝试这些变化:

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

int main() 
{    
    char s[100];  
    int i; 
    FILE * myfile; 

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r"); 

    // Check that fopen went fine 
    if (!myfile) 
    { 
     printf("Failed to open file\n"); 
     return 1; 
    } 

    while(fscanf(myfile, "%99s", s) == 1) 
         // ^^ 
         // Never read more than 99 chars (i.e. 99 + a terminating null byte) 
     { 
      for (i=0 ; i<strlen(s) ; i++) 
         // ^^^^^^ 
         // Only iterate over the valid chars 
       { 
        if (s[i] == 'Α') 
         { printf("A") ; } 
        else 
        if (s[i] == 'Β') 
         { printf("V") ; } 
     } 
} 
+0

我试试这个确切的代码。首先,它没有识别strlen(s),当我用一开始就将它取代时,我得到了分段错误 –

+0

哦,你是对的..但是,只是尝试过它仍然是分段错误 –

+0

更新:我忘记了写一行它确实返回无法打开文件。所以我该怎么做? –