#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
FILE* fp;
FILE* ptr;
int cha, charac = 0, lines = 0, spaces = 0;
char ch;
fp = fopen("f.txt", "r");
while (ch != EOF) {
ch = fgetc(fp);
printf("%c", ch);
}
fclose(fp);
fp = fopen("fi.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2021);
fclose(fp);
if (fp == NULL)
printf("Can't Open File");
else {
while ((cha = fgetc(fp)) != EOF) {
charac++;
if (ch == ' ')
spaces++;
if (ch == 'n')
lines++;
}
fclose(fp);
printf("Character %dn", charac);
printf("Spaces %dn", spaces);
printf("Lines %dn", lines);
}
}
如果您尝试编写读取文件的代码,请计算行/空格/字符数并将其打印到屏幕上。然后写另一个文件,其中包括"我们在2021年"。对吧?确认下面的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char * *argv, char * *envp) {
FILE *fRead;
FILE *fWrite;
int characters = 0, lines = 0, spaces = 0;
fRead = fopen("/Users/Shared/CommonAll/file1.txt", "r");
if (fRead == NULL) {
printf("ERROR: Could not open the SOURCE file!");
return (EXIT_FAILURE);
}
else {
char singleChar;
while(1){
singleChar = fgetc(fRead);
if(singleChar == EOF || (int)(singleChar) == -1){
break;
}
else if (singleChar == ' '){
spaces++;
}
else if ((int) (singleChar) == 13) {
lines++;
}
else {
characters++;
}
printf("%c", singleChar);
}
}
fclose(fRead);
fWrite = fopen("/Users/Shared/CommonAll/file2.txt", "w+");
if (fWrite == NULL) {
printf("ERROR: Could not open the TARGET file!");
return (EXIT_FAILURE);
}
fprintf(fWrite, "%s %s %s %d", "We", "are", "in", 2021);
fclose(fWrite);
printf("nCharacter %dn", characters);
printf("Spaces %dn", spaces);
printf("Lines %dn", lines);
return (EXIT_SUCCESS);
}