c - 尝试从文件中获取字符串并访问字符串中的各个字母时程序崩溃

标签 c string loops pointers file-handling

我正在创建一个 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;
}

最佳答案

在函数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
}

关于c - 尝试从文件中获取字符串并访问字符串中的各个字母时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883605/

相关文章:

loops - x86 NASM 程序集 - 输入问题

c - 使用 strtok_r 时 malloc.c 断言失败

c - 我如何从 CodeWarrior 中的 C 文件调用汇编代码?

java - 如何检查字符串是否包含字符串数组的元素?

javascript - 如何使用 javascript 分隔这些字符串

python - 让 Psychopy 构建器每 3 张图像后等待响应

c - 如何将一维数组从 fortran 传递到 c

c++ - 独立于操作系统的清除缓冲区

PHP 和弦转置器

c - 嵌入式 C 语言中的 "Super Loop"是什么?