gpt4 book ai didi

c - 在c中读取和写入文件

转载 作者:行者123 更新时间:2023-11-30 19:10:07 25 4
gpt4 key购买 nike

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

#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]);
}
}

最佳答案

您的程序存在几个问题。

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

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

第三个问题是这一行:

strcpy(text[i],date);

strcpy() 的参数必须是字符串,即指向以 null 结尾的 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);
}
}

关于c - 在c中读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com