提取txt文件里的字符串存到数组中c语言
时间: 2023-12-11 18:04:36 浏览: 62
可以使用C语言中的文件操作函数来读取txt文件并提取其中的字符串。
以下是一个示例代码,可以读取文件名为filename的txt文件,并将其中的所有字符串存储到一个动态分配的数组中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 100 // 最大字符串长度
int main()
{
char filename[] = "example.txt"; // 文件名
char* string_array = NULL; // 用于存储字符串的数组
int array_size = 0; // 数组大小
int string_count = 0; // 字符串数量
char buffer[MAX_STRING_LENGTH]; // 缓冲区
FILE* fp = fopen(filename, "r"); // 打开文件
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return -1;
}
// 逐行读取文件内容,提取其中的字符串
while (fgets(buffer, MAX_STRING_LENGTH, fp) != NULL) {
// 去掉行末的换行符
int len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[len-1] = '\0';
len--;
}
// 将字符串添加到数组中
if (len > 0) {
string_array = realloc(string_array, (array_size + len + 1) * sizeof(char));
strncpy(string_array + array_size, buffer, len + 1);
array_size += len + 1;
string_count++;
}
}
fclose(fp);
// 输出结果
printf("%d strings found:\n", string_count);
for (int i = 0; i < string_count; i++) {
printf("%s\n", string_array + i*(MAX_STRING_LENGTH+1));
}
free(string_array);
return 0;
}
```
需要注意的是,上述代码使用了动态分配内存的方式来存储字符串数组。可以通过realloc函数动态增加数组的大小,以容纳更多的字符串。在输出结果后,需要使用free函数释放动态分配的内存。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)