C语言文件昨日可打开今日找不到原因及字母出现次数统计咨询
Troubleshooting "File Not Found" Error & Counting Letter Occurrences
Hey there, let's break down your two questions one by one—this stuff happens more often than you might think!
1. Why is the file suddenly not found?
Even if you didn’t touch your code, there are a handful of common reasons this could happen:
- Changed working directory: When your program runs, it looks for the file in its current working directory. If you ran the code from a different folder today (e.g., your IDE’s run path shifted, or you opened the terminal in a new location), the program can’t locate the file. Try using the full absolute path (like
C:\Docs\mytext.txton Windows or/home/you/mytext.txton Linux/macOS) instead of just the filename. - File moved/renamed/deleted: It’s easy to accidentally drag a file to another folder, rename it, or have it cleaned up by a system tool. Double-check the file’s location and exact name to confirm it’s still where you expect.
- Case sensitivity (Linux/macOS): Unix-like systems treat filenames as case-sensitive—
MyFile.txtandmyfile.txtare two different files. Make sure you’re entering the exact capitalization when prompted. - Unsafe
gets()behavior: Thegets()function is risky because it doesn’t handle input limits or trailing spaces well. If you accidentally added a space when typing the filename,gets()would include it, leading the program to look for a file with that extra space. Swap it out forfgets(file_name, sizeof(file_name), stdin)to fix this (we’ll show you how in the code below).
2. How to count occurrences of individual letters?
To track how many times each letter (a-z) appears, we can use an array to store counts. Here’s a modified version of your code that adds this functionality (plus fixes the gets() issue):
#include <stdio.h> #include <stdlib.h> #include <ctype.h> // For tolower() to handle case insensitivity int main() { char ch, file_name[25]; FILE *fp; int letter_counts[26] = {0}; // Initialize all counts to 0 // Prompt for filename (safer than gets()) printf("Welche Datei soll aufgerufen werden?\n"); fgets(file_name, sizeof(file_name), stdin); // Remove the trailing newline that fgets() adds size_t len = 0; while (file_name[len] != '\0') { if (file_name[len] == '\n') { file_name[len] = '\0'; break; } len++; } fp = fopen(file_name, "r"); // Read mode if (fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } // Read file content and count letters printf("The contents of %s file are:\n", file_name); while((ch = fgetc(fp)) != EOF) { printf("%c", ch); // Convert to lowercase to count uppercase/lowercase as the same char lower_ch = tolower(ch); // Check if it's a letter a-z if (lower_ch >= 'a' && lower_ch <= 'z') { letter_counts[lower_ch - 'a']++; // Increment the corresponding count } } // Print the final letter counts printf("\n\nLetter occurrence counts:\n"); for (int i = 0; i < 26; i++) { if (letter_counts[i] > 0) { printf("%c: %d\n", 'a' + i, letter_counts[i]); } } fclose(fp); return 0; }
Quick breakdown of the changes:
letter_countsarray: Each index maps to a letter (0 = 'a', 1 = 'b', ..., 25 = 'z') and tracks how many times it appears.tolower(): Converts all characters to lowercase so "A" and "a" are counted together (remove this if you want separate counts for uppercase and lowercase).fgets()replacement: Fixes the unsafegets()function and strips the trailing newline thatfgets()automatically adds to input.- Count output: After reading the file, we loop through the array to print only letters that actually appeared.
内容的提问来源于stack exchange,提问作者user12742406
相关产品推荐
相关产品推荐

