연습문제
C 파일 입출력 문제1
오군_
2023. 5. 24. 22:28
반응형
// 문제 A,a 로 시작하는 단어 P,p 로 시작하는 단어의 수 구하기
void CreateFile()
{
char words[100];
FILE* file = fopen("text.txt", "wt");
if (file == NULL)
{
puts("파일 오류");
return -1;
}
printf("단어 다섯개 입력 : \n");
for (int i = 0; i < 5; i++)
{
printf("%d번째 단어 입력 : ", i+1);
fgets(words, sizeof(words), stdin);
fprintf(file, "%s", words);
}
fclose(file);
}
int countWords(const char* filename) {
FILE* file = fopen(filename, "rt");
if (file == NULL) {
printf("파일을 열 수 없습니다.\n");
return -1;
}
int countA = 0;
int countP = 0;
char word[100];
while (fscanf(file, "%s", word) != EOF) {
if ((word[0] == 'A' || word[0] == 'a')) {
countA++;
}
else if ((word[0] == 'P' || word[0] == 'p')) {
countP++;
}
}
printf("A로 시작하는 단어의 수: %d\n", countA);
printf("P로 시작하는 단어의 수: %d\n", countP);
fclose(file);
return 0;
}
int main()
{
char* filename = "text.txt";
CreateFile();
countWords(filename);
return 0;
}
반응형
반응형