在c中读写文件

时间:2017-01-26 20:06:42

标签: c file

我需要用大写的字符串写入一个文件,然后用小写字母显示在屏幕上。之后,我需要将新文本写入文件(小写一个)。我写了一些代码,但它不起作用。当我运行它时,我的文件似乎完好无损,并且转换为小写不起作用

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

void main(void) {
    int i;
    char date;
    char text[100];
    FILE *file;
    FILE *file1;
    file = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","r");
    file1 = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","w");

    printf("\nSe citeste fisierul si se copiaza textul:\n ");

    if(file) {
        while ((date = getc(file)) != EOF) {
            putchar(tolower(date));
            for (i=0;i<27;i++) {
                strcpy(text[i],date);
            }
        }    
    }

    if (file1) {
        for (i=0;i<27;i++)
        fprintf(file1,"%c",text[i]);
    }
}

1 个答案:

答案 0 :(得分:1)

您的计划存在一些问题。

首先,getc()返回int,而不是char。这是必要的,因此它可以保留EOF,因为这不是有效的char值。因此,您需要将date声明为int

当您解决此问题时,由于第二个问题,您会注意到程序会立即结束。这是因为您使用相同的文件进行输入和输出。当您以写入模式打开文件时,会清空文件,因此无需读取任何内容。您应该等到读完文件后再打开输出文件。

第三个问题是这一行:

strcpy(text[i],date);

strcpy()的参数必须是字符串,即指向以char为空的终止数组的指针,但text[i]datechar(单个字符) )。确保已启用编译器警告 - 该行应警告您不正确的参数类型。要复制单个字符,只需使用普通作业:

text[i] = date;

但我并不确定您想要将date复制到每个text[i]的循环中。我怀疑你想要将你读过的每个字符复制到text的下一个元素中,而不是复制到所有字符中。

最后,当您保存到text时,您没有保存小写版本。

这是一个纠正过的程序。我还在text添加了一个空终止符,并更改了第二个循环来检查它,而不是硬编码长度为27。

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

void main(void) {
    int i = 0;
    int date;
    char text[100];
    FILE *file;
    FILE *file1;
    file = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","r");

    printf("\nSe citeste fisierul si se copiaza textul:\n ");

    if(file) {
        while ((date = getc(file)) != EOF) {
            putchar(tolower(date));
            text[i++] = tolower(date);
        }
        text[i] = '\0'; 
        fclose(file);
    } else {
        printf("Can't open input file\n");
        exit(1);
    }

    file1 = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","w");
    if (file1) {
        for (i=0;text[i] != '\0';i++)
            fprintf(file1,"%c",text[i]);
        fclose(file1);

    } else {
        printf("Can't open output file\n");
        exit(1);
    }
}