[英]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.