【问题标题】:Program crashing when reading blank line - c读取空行时程序崩溃 - c
【发布时间】:2017-10-11 03:07:29
【问题描述】:

我最近开始处理文件,但遇到了错误。我有一个.txt。包含以下字符串的文件:

a|10

b|5

我的问题是当我读取空白行时,即使我在代码中有条件,它也会以某种方式崩溃。调试时,我可以看到该行收到一个“\n”,但程序在这种情况下无法识别它并且它崩溃了。

void delete_prod(void)
{
FILE *pfile;
char line[21];
char *buffer;
char *ptr;
char produto_nome[21];
char produto_quantidade[21];

char quantidade_nova[21];
char teste[21];
char barra_linha[]="\n";

buffer = (char *) malloc(1000*sizeof(char));
memset(buffer, 0, 1000*sizeof(char));
ptr = buffer;

printf("material:");
scanf("%s",teste);

pfile = fopen("registos.txt", "r");

while(!feof(pfile))
{
    int i=0;
    for(i; i<21;i++)
    {
        line[i] = 0;
    }
    fgets(line, 21, pfile);
    if(line != NULL || line != "\n")
    {
        strcpy(produto_nome, strtok(line ,"|"));
        strcpy(produto_quantidade, strtok(NULL, "|"));

        if((strcmp(produto_nome,teste) == 0))
        {
            //DO THE REST OF THE WORK HERE
            printf("HERE");
        }
        else
        {
            printf("ERROR");
        }
    }
}
fclose(pfile);
}

一直在这里研究,但没有找到任何可以解决我问题的东西。 在此先感谢,我希望我清楚地解释了这个问题。

【问题讨论】:

标签: c file


【解决方案1】:

考虑所有输入的 fgets。
strpbrk 可用于查看该行是否包含 |
sscanf 可以解析该行以查看是否有两个值。

void delete_prod(void)
{
    FILE *pfile;
    char line[21];
    char *buffer;
    char *ptr;
    char produto_nome[21];
    char produto_quantidade[21];

    char quantidade_nova[21];
    char teste[21];
    char barra_linha[]="\n";

    buffer = (char *) malloc(1000*sizeof(char));
    memset(buffer, 0, 1000*sizeof(char));
    ptr = buffer;

    printf("material:");
    fgets ( teste, sizeof teste, stdin);
    teste[strcspn ( teste, "\n")] = '\0';//remove newline

    pfile = fopen("registos.txt", "r");

    while( fgets ( line, sizeof line, pfile))
    {
        if( strpbrk ( line, "|"))//the line contains a |
        {
            //sscanf for two items
            result = sscanf ( line, "%20[^|]|%20s", procuto_nome, produto_quantidade);

            if(result == 2) {
                if((strcmp(produto_nome,teste) == 0))
                {
                    //DO THE REST OF THE WORK HERE
                    printf("HERE");
                }
                else
                {
                    printf("ERROR");
                }
            }
            else {
                printf ( "ERROR line did not contain two values\n");
            }
        }
        else {
            printf ( "ERROR line does not contain |\n");
        }
    }
    fclose(pfile);
}

【讨论】:

    【解决方案2】:

    您检查空行的条件编码不正确。

    改变

    line != "\n"

    line[0] != '\n'

    因为这个条件不正确,所以它总是得到满足。后来在if 块内strtok 返回null,因为空行中没有管道符号。如此有效,您将 null 传递给导致程序崩溃的 strcpy 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2012-01-22
      • 1970-01-01
      相关资源
      最近更新 更多