需要获得更好的代码来将文件读入变量

时间:2014-12-13 19:00:34

标签: c

目前有此代码(见下文)。它工作正常,但我需要能够管理空行,还有注释行。这些注释行定义为:拥有"#"作为一行的第一个字符。最初,我只循环100次,因为我也将存储限制为100,但是当跳过空行和备注行时,100的简单计数器不起作用。尽管如此,只有前100条有效行可以被读取,并存储在" menu_choices"变量。此外,每行的长度应限制为100个字符(或者,我有一个100个字符的变量,所以99 +输入)。我也需要包含它。我不能决定我需要一个IF声明,或者一段时间,或者其他什么。

int x;  
char inputfile[512];  
char menu_number[100];  
char menu_choices[100][100];  

printf("\nopening:%s\n",inputfile);  
p_datafile=fopen(inputfile,"r");  

x=1;  
//for (x=1 ; x <= 100 ; x++ )  
do  
{
    // read next line into variable  
    fgets(menu_choices[x],100,p_datafile);  
    if ( strcmp ( menu_choices[x] , "" ) == 0 ) break;  
    if ( strncmp(menu_choices[x],"#",1) )  
    {  
        printf("%d[lngth=%d]=%s",x,strlen(menu_choices[x]),menu_choices[x]);  
        x++;  
    }  
    else  
    {  
        printf("\n LINE WITH #");  
    }  
    sleep (1);  
} while (1);  

fclose(inputfile);

你能改进上面的代码吗?

3 个答案:

答案 0 :(得分:1)

我不太确定我是否理解了您的问题,但似乎以下几点可以帮助您实现目标。

  1. NULL上添加p_datafile项检查,以检查fopen()是否成功。 [假设p_datafile已定义为FILE *,您不会向我们展示哪一部分。]
  2. break;之后
  3. 而不是if ( strcmp ( menu_choices[x] , "" ) == 0 ),请使用continue
  4. continue;阻止内printf("\n LINE WITH #");之后添加else
  5. if...else阻止后
  6. ,检查是否{x == 100),如果为真,break;
  7. fclose()中,使用p_datafile。它需要文件指针,而不是文件名。

答案 1 :(得分:1)

要实现您所描述的内容,可能会有效。

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

int
main()
{
    int   lineCount;
    char  filename[512];
    /* if you want to read 100 characters you need 1 extra for the termination 0 */
    char  menu_choices[100][100 + 1 /* termination 0 */];
    int   extraLines;
    int   lineLength;
    FILE *p_datafile; // p_datafile was not declared...
    int   character;
    int   skipLine;

    printf("enter filename please: ");
    scanf("%511s", filename);
    printf("\topening:%s\n", filename);

    lineCount  = 0;
    p_datafile = fopen(filename, "r");
    if (p_datafile == NULL)
        return 0; // or perhaps return a value, since there is no context here I don't know
    memset(menu_choices[0], 0, 101);

    extraLines = 0;
    lineLength = 0;
    skipLine   = 0;
    while ((p_datafile != NULL) && ((character = getc(p_datafile)) != EOF))
    {
        if (character == '\n')
        {
            if ((lineLength > 0) && (skipLine == 0))
            {

                menu_choices[lineCount][lineLength] = 0;
                lineCount                          += 1;

                printf("valid line %d [length -> %d] -> %s\n", lineCount, lineLength, menu_choices[lineCount - 1]);

                memset(menu_choices[lineCount], 0, 101);
            }
            else if (skipLine != 0)
            {
                fprintf(stderr, "line starts with #\n");
                extraLines += 1;
            }
            else if (lineLength == 0)
            {
                fprintf(stderr, "line is empty\n");
                extraLines += 1;
            }
            skipLine   = 0;
            lineLength = 0;
        }
        else if ((lineLength == 0) && (isspace(character) != 0))
        {
            /* Ignore spaces if non-space characters where not found yet. */
        }
        else
        {
            if ((lineLength == 0) && (character == '#'))
                skipLine = 1; /* Ignore this line, it starts with */
            else if (lineLength < 100)
            {
                menu_choices[lineCount][lineLength] = (char)character;
                lineLength                         += 1;
            }
        }
    }
    fclose(p_datafile); // the FILE * not the filename

    return 0;
}

答案 2 :(得分:0)

一个答案就在我面前,但无论如何我都会发帖。请记住,fgets()也会读取newline,因此我已经测试/删除了它。此外,您的索引:尽可能使用基于0的索引,并在输入和输出点为人类0..1..之间进行任何调整。

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

int main()
{
    int x, len;  
    char inputfile[512] = "lines.txt";
    char menu_number[100];  
    char menu_choices[100][100];  
    FILE *p_datafile;

    printf ("\nopening:%s\n",inputfile);  
    p_datafile=fopen (inputfile,"rt");           // it's a text file
    if (p_datafile == NULL) {
        printf ("Can't open file %s\n", inputfile);
        exit (1);
    }

    x = 0;                  // get the array indexing right  
    while (x<100 && fgets(menu_choices[x], 100, p_datafile)) {
        if (menu_choices[x][0] != '\n' && menu_choices[x][0] != '#') {
            len = strlen (menu_choices[x]);
            if (menu_choices[x][len-1] == '\n')  // remove newline
                menu_choices[x][len-1] = 0;
            printf ("%s\n", menu_choices[x]);
            // sleep (1);  
            x++;
        }
    }

    fclose(p_datafile);     // corrected mistake (don't use filename)
    return 0;
}

输入文件:

Line 1
Line 02

#not line 3
line three

节目输出:

opening:lines.txt
Line 1
Line 02
line three