[英]Reading and writing into a file in c
我需要用大写的一些字符串写入文件,然后用小写在屏幕上显示。 之后,我需要将新文本(小写字母)写入文件。 我写了一些代码,但它不起作用。 当我运行它时,我的文件似乎完好无损并且转换为小写不起作用
#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()
的参数必须是字符串,即指向以空char
结尾的char
数组的指针,但text[i]
和date
是char
(单个字符)。 确保您启用了编译器警告——该行应该警告您有关不正确的参数类型。 要复制单个字符,只需使用普通赋值:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.