如何将文件中的字符串复制到二维字符变量中?附C语言代码片段
Hey there! Let's walk through how to finish your implementation of reading strings from a file into a 2D character array, building on the code you've already started.
First, you need to finish counting the total number of words and the longest word length in the file. Here's how to fill in that missing logic:
// CHECK WORDS COUNT AND MAX STRING LENGTH char chr; int word_count = 0; int chrcount = 0; int max_chrcount = 0; int in_word = 0; // Flag to track if we're inside a word while ((chr = fgetc(fp)) != EOF) { if (chr == ' ' || chr == '\n' || chr == '\t') { if (in_word) { // End of a word word_count++; if (chrcount > max_chrcount) { max_chrcount = chrcount; } chrcount = 0; in_word = 0; } } else { // Part of a word chrcount++; in_word = 1; } } // Don't forget the last word if file doesn't end with whitespace if (in_word) { word_count++; if (chrcount > max_chrcount) { max_chrcount = chrcount; } }
This code tracks when we enter/exit a word (using whitespace as delimiters), counts each word, and keeps track of the longest word's length.
Now that we know how many words we have and the longest word length, we can allocate a 2D character array to store them. We'll use dynamic allocation for flexibility:
// Allocate array of pointers (one per word) char **words = malloc(word_count * sizeof(char *)); if (words == NULL) { printf("Memory allocation failed!\n"); fclose(fp); exit(1); } // Allocate memory for each word (plus 1 for null terminator) for (int i = 0; i < word_count; i++) { words[i] = malloc((max_chrcount + 1) * sizeof(char)); if (words[i] == NULL) { printf("Memory allocation failed!\n"); // Clean up already allocated memory for (int j = 0; j < i; j++) { free(words[j]); } free(words); fclose(fp); exit(1); } }
We need to reset the file pointer to the start of the file, then read each word one by one, convert it to lowercase, and store it in our array:
rewind(fp); // Reset file pointer to start int index = 0; char temp_word[max_chrcount + 1]; // Temporary buffer for each word while (fscanf(fp, "%s", temp_word) != EOF && index < word_count) { lower_string(temp_word); // Convert to lowercase strcpy(words[index], temp_word); // Copy to our 2D array index++; }
To verify everything works, you can print out all the words:
printf("Words from file (lowercase):\n"); for (int i = 0; i < word_count; i++) { printf("%s\n", words[i]); }
Don't forget to free the allocated memory and close the file to avoid leaks:
// Free each word's memory for (int i = 0; i < word_count; i++) { free(words[i]); } // Free the array of pointers free(words); fclose(fp);
Putting it all together, here's the full working code:
#include <stdio.h> #include <stdlib.h> #include <string.h> void lower_string(char s[]) { int c = 0; while (s[c] != '\0') { if (s[c] >= 'A' && s[c] <= 'Z') { s[c] = s[c] + 32; } c++; } } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage : WI_11SI2_12S17048.exe [nama file].txt \n"); exit(0); } const char *filename = argv[1]; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("file doesn't exist.\n"); exit(1); } // CHECK WORDS COUNT AND MAX STRING LENGTH char chr; int word_count = 0; int chrcount = 0; int max_chrcount = 0; int in_word = 0; while ((chr = fgetc(fp)) != EOF) { if (chr == ' ' || chr == '\n' || chr == '\t') { if (in_word) { word_count++; if (chrcount > max_chrcount) { max_chrcount = chrcount; } chrcount = 0; in_word = 0; } } else { chrcount++; in_word = 1; } } if (in_word) { word_count++; if (chrcount > max_chrcount) { max_chrcount = chrcount; } } // Allocate 2D array char **words = malloc(word_count * sizeof(char *)); if (words == NULL) { printf("Memory allocation failed!\n"); fclose(fp); exit(1); } for (int i = 0; i < word_count; i++) { words[i] = malloc((max_chrcount + 1) * sizeof(char)); if (words[i] == NULL) { printf("Memory allocation failed!\n"); for (int j = 0; j < i; j++) { free(words[j]); } free(words); fclose(fp); exit(1); } } // Read words into array rewind(fp); int index = 0; char temp_word[max_chrcount + 1]; while (fscanf(fp, "%s", temp_word) != EOF && index < word_count) { lower_string(temp_word); strcpy(words[index], temp_word); index++; } // Example: Print all words printf("Words from file (lowercase):\n"); for (int i = 0; i < word_count; i++) { printf("%s\n", words[i]); } // Cleanup for (int i = 0; i < word_count; i++) { free(words[i]); } free(words); fclose(fp); return 0; }
- We use
fscanf("%s")here which splits words on whitespace—if you need to handle words with apostrophes or hyphens, you'd need a more custom parsing logic. - Always check for
mallocfailures to avoid crashes from null pointers. - Don't skip cleaning up memory and closing the file—this prevents memory leaks and resource issues.
内容的提问来源于stack exchange,提问作者Learner

