如何统计.txt文件内的条目数量,用于遍历赋值到结构体数组?
Looks like you need to count the number of whitespace-separated "entries" (words) in a text file (like your students.txt example with 18 entries) so you can properly size a struct array to hold them. Here are a couple of reliable, straightforward approaches in C:
Method 1: Using fscanf for Simple Counting
This is the easiest method for most cases. Since fscanf automatically skips whitespace (spaces, newlines, tabs), we can loop reading entries until we hit the end of the file, incrementing a counter each time.
#include <stdio.h> #include <stdlib.h> int count_entries(const char *filename) { FILE *file = fopen(filename, "r"); if (!file) { perror("Failed to open file"); return -1; // Return error code if file can't be opened } char buffer[256]; // Adjust buffer size based on your max entry length int count = 0; // Keep reading entries until EOF is reached while (fscanf(file, "%s", buffer) != EOF) { count++; } fclose(file); return count; }
How to Use This:
- Call the function to get your entry count:
int entry_count = count_entries("students.txt"); - Validate the count (if it's
-1, handle the file error; if0, no entries exist). - Allocate your struct array using the count:
// Define your struct based on the entry format typedef struct { char username[50]; long timestamp; char filename[100]; } FileEntry; int main() { int entry_count = count_entries("students.txt"); if (entry_count <= 0) { fprintf(stderr, "No entries found or file access error.\n"); return 1; } // Allocate memory for the struct array FileEntry *entries = malloc(entry_count * sizeof(FileEntry)); if (!entries) { perror("Failed to allocate memory"); return 1; } // Now you can re-open the file and read entries into the struct array... // Don't forget to free(entries) when you're done with it! return 0; }
Method 2: Character-by-Character Counting (More Control)
If you need finer control over what counts as a separator (or want to avoid buffer size limits), read the file character by character and track word boundaries:
#include <stdio.h> #include <ctype.h> #include <stdlib.h> int count_entries(const char *filename) { FILE *file = fopen(filename, "r"); if (!file) { perror("Failed to open file"); return -1; } int count = 0; int in_entry = 0; // 0 = not in an entry, 1 = inside an entry int c; while ((c = fgetc(file)) != EOF) { if (isspace(c)) { in_entry = 0; // We hit whitespace, exit the current entry } else if (!in_entry) { in_entry = 1; // We started a new entry count++; } } fclose(file); return count; }
This method counts any sequence of non-whitespace characters as a single entry, which perfectly matches your example's requirement.
Key Tips:
- Error Handling: Always check if the file opens successfully—
perror()will tell you exactly what went wrong (e.g., file not found). - Memory Management: After using your struct array, make sure to
free(entries)to avoid memory leaks. - Reading into Structs: Once you have the count, re-open the file and read entries using
fscanftailored to your struct (e.g.,fscanf(file, "%s %ld %s", entries[i].username, &entries[i].timestamp, entries[i].filename)for your example format).
Content of the question originates from Stack Exchange, asked by Great Scott

