【问题标题】:Program crashes while trying to get a string from file and access indvidual letters in the string尝试从文件中获取字符串并访问字符串中的单个字母时程序崩溃
【发布时间】:2015-12-29 06:33:13
【问题描述】:

我正在创建一个 C 程序来将所有小写字母转换为大写字母,反之亦然。在 C 程序中,我试图从文本文件中获取一个字符串并访问每个字符。但是我的程序崩溃了。我在这里做的错误是什么?以下是我的代码:

 //Program to read contents from a source file and convert the lower case characters to a upper case and vice versa and print it on a target file

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

void merge(FILE *fp,int n,char *fdata,FILE *fpr)
{
    char change_case[1000];
    int loop = 0;

    while(fgets(fdata,n,fp)!=NULL)
    {
        fgets(fdata,n,fp);

        //printf("%s",fdata);

        if ((*(fdata+loop) >= 65) && (*(fdata+loop) <= 90))
        {
            printf("%c",*(fdata+loop));
            change_case[loop] = *(fdata+loop)+32;
        }
        else if ((*(fdata+loop) >= 97) && ((*fdata+loop) <= 122))
        {
            printf("%c",*(fdata+loop));
            change_case[loop] = *(fdata+loop)-32;
        }
        else
        {
            change_case[loop] = *(fdata+loop);
        }
        loop++;

        fpr = fopen("Text File 3.dat","w");

        if (fpr == NULL)
        {
            printf("Error in accessing / writing the target file"); 
        }
        else
        {
            fputs(change_case,fpr);
            printf("Line written successfully : %s\n", change_case);
        }
    }
}

int main()
{
    FILE *sfp, *tfp; //declaring a file pointer for source file and target file
    char *fdata;
    int n = 1000;
    sfp = fopen("Text File 1.txt","r");

    if (sfp == NULL)
    {
        printf("Error in reading the source file\n");
    }

    else
    {
        merge(sfp,n,fdata,tfp);
    }   

    fclose(sfp);

return 0;
}

【问题讨论】:

标签: c string loops pointers file-handling


【解决方案1】:

在函数void merge(FILE *fp,int n,char *fdata,FILE *fpr)-

fgets(fdata,n,fp);         // you tend to write at invalid location 

内存未分配给 fdata 。你需要给它分配内存。

fdata=malloc(n);     // check its return and also remember to free it

注意 - 不要使用 while!feof(fp)

你可以这样做 -

while(fgets(fdata,n,fp)!=NULL)
{
     // your code
}

【讨论】:

  • @KiranCK 如果有大数据,那么您需要分配更多内存。如果更新了分配更多内存的答案。
  • 输入文件的字符数小于100
  • @KiranCK 我不明白 carsh 。你确定这是代码?
  • @KiranCK 您不应该更新有问题的原始代码。请不要投出malloc的结果。
  • 我已经编辑并粘贴了包含您指出的更新的代码。它仍然崩溃。我使用带有 Borland C 5.5.1 的代码块作为编译器
猜你喜欢
  • 2018-04-24
  • 2020-02-16
  • 2015-08-06
  • 1970-01-01
  • 2013-01-07
  • 2018-07-11
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多