用c语言写函数:函数名为Chars load_file_to_Chars;形式参数为FILE * fp ;load the content of a file in a char sequence ;If fp is NULL, return an empty Chars. Otherwise, a Chars is made, its space allocated on the Heap. Each byte of the file is copied as a character in the Chars. The Chars is fitting, whose number of characters is the same as in the file. Return the Chars.;I
时间: 2023-02-16 12:21:14 浏览: 93
Chars load_file_to_Chars(FILE *fp) {
Chars chars;
if (fp == NULL) {
chars.len = 0;
chars.s = NULL;
return chars;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
chars.len = size;
chars.s = (char *)malloc(size + 1);
fseek(fp, 0, SEEK_SET);
fread(chars.s, 1, size, fp);
chars.s[size] = '\0';
return chars;
}
注意:这里假设你有一个Chars的结构体定义,例如
typedef struct {
int len;
char *s;
} Chars;
相关问题
用c语言写一段代码,函数名为void reverse_chars_in_place;形式参数为char *cs, Uint len;In the space of s, reverse the character sequence. I.e. abc becomes cba. nothing is returned.
```
void reverse_chars_in_place(char *cs, Uint len) {
Uint i;
char tmp;
for (i = 0; i < len / 2; ++i) {
tmp = cs[i];
cs[i] = cs[len - i - 1];
cs[len - i - 1] = tmp;
}
}
```
注意:在这段代码中,我假设 Uint 类型已经被定义为无符号整型。
帮我用c语言写一段代码:A word is a sequence characters such that each of them is not a whitespace, nor a \0. Find the first token in a CS;函数名为Chars find_word;形式参数为const char* cs, Uint len;Find the first (left-most) token in the CS. If found, return a Chars whose addr is of the first character in the token, and whose len is the number of chars in the token. Otherwise, an empty Chars is returned (with NULL addr and 0 len).
以下是示例代码:
```
typedef struct {
const char* addr;
Uint len;
} Chars;
Chars find_word(const char* cs, Uint len) {
Chars result = {NULL, 0};
for (Uint i = 0; i < len; i++) {
if (cs[i] != ' ' && cs[i] != '\0') {
result.addr = cs + i;
result.len = 1;
break;
}
}
return result;
}
```
该代码将从 CS 的开头开始遍历字符串,找到第一个非空格和非 NULL 字符,并返回包含该字符的 Chars 结构体。如果找不到,则返回一个 addr 和 len 均为 NULL 的空 Chars 结构体。
阅读全文