c语言将文本内容赋值给数组
时间: 2023-09-05 09:15:10 浏览: 46
可以使用fgets()函数将文本内容一行一行地赋值给数组,示例代码如下:
```c
#include <stdio.h>
#define MAX_LENGTH 1000
int main() {
char text[MAX_LENGTH];
FILE *fp;
fp = fopen("text.txt", "r"); // 打开文本文件
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
while (fgets(text, MAX_LENGTH, fp) != NULL) { // 一行一行读取文本内容
printf("%s", text); // 输出读取到的内容
}
fclose(fp); // 关闭文件
return 0;
}
```
此示例代码将打开名为"test.txt"的文本文件,并将每一行的内容赋值给名为"text"的字符数组。您可以根据实际需要修改数组的大小和文件名。
相关问题
c语言将txt文本每一行内容赋值给结构体的每行元素
假设结构体定义如下:
```c
#define MAX_LINE_LEN 100
typedef struct {
char content[MAX_LINE_LEN];
} Line;
```
可以按照行读取文本文件,然后将每一行内容分别赋值给结构体的每行元素,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define MAX_LINES 100
typedef struct {
char content[MAX_LINE_LEN];
} Line;
int main() {
FILE* fp;
char buf[MAX_LINE_LEN];
Line lines[MAX_LINES];
int i = 0;
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
while (fgets(buf, MAX_LINE_LEN, fp) != NULL) {
if (i == MAX_LINES) {
printf("Too many lines\n");
exit(1);
}
buf[strcspn(buf, "\n")] = '\0'; // remove trailing newline
strcpy(lines[i].content, buf);
i++;
}
fclose(fp);
// print out the lines
for (int j = 0; j < i; j++) {
printf("Line %d: %s\n", j+1, lines[j].content);
}
return 0;
}
```
其中,`fgets` 函数每次读取一行文本,`strcspn` 函数查找字符串中第一个匹配指定字符集合中的字符,并返回其位置,从而将行末的换行符替换为字符串结束符号。然后,使用 `strcpy` 函数将该行内容拷贝到结构体的 `content` 字段中,最后将结构体数组进行遍历,打印出每一行的内容。
c语言将txt文本每一行内容进行类型转换后并赋值给结构体的每行元素
假设文本文件中每行都是一个整数,结构体定义如下:
```c
#define MAX_LINE_LEN 100
typedef struct {
int value;
} Line;
```
可以按照行读取文本文件,然后将每一行内容进行类型转换后分别赋值给结构体的每行元素,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define MAX_LINES 100
typedef struct {
int value;
} Line;
int main() {
FILE* fp;
char buf[MAX_LINE_LEN];
Line lines[MAX_LINES];
int i = 0;
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
exit(1);
}
while (fgets(buf, MAX_LINE_LEN, fp) != NULL) {
if (i == MAX_LINES) {
printf("Too many lines\n");
exit(1);
}
buf[strcspn(buf, "\n")] = '\0'; // remove trailing newline
lines[i].value = atoi(buf);
i++;
}
fclose(fp);
// print out the values
for (int j = 0; j < i; j++) {
printf("Line %d: %d\n", j+1, lines[j].value);
}
return 0;
}
```
其中,`atoi` 函数将字符串转换为整数,然后将该整数赋值给结构体的 `value` 字段。最后将结构体数组进行遍历,打印出每一行的整数值。