我试图使用一个函数将文本文件的每3个字符放入一个数组指针。

我有一个char *数组的指针。 我的程序的一部分将读取文本文件,获取char1 2 3并将其存储在数组[0]中。 然后,我不想读4 5 6,而是希望我的程序读取2 3 4,3 4 5,依此类推,直到单词结束,跳过空格继续第二个单词。 我还应该使用fgetc吗? 有什么建议? 谢谢。

[UPDATE]
你必须 :

  • 读取所有文件并将其内容放入char *
  • 解析字符串,获取当前字符并检查是否定义了2个下一个字符
  • 把它放在你的数组中(这里我只用printf显示)

这是一个例子:

int main(int ac, char **av) { int fd; char *str; int size; int i; struct stat sb; i = -1; if (ac != 2) return (84); if (!(fd = open(av[1], O_RDONLY))) return (84); if (stat(av[1], &sb) == -1) return (84); size = sb.st_size; // Get the size of the file if (!(str = malloc(sizeof(char) * (size + 1)))) // Allocate enought memory return (84); if (read(fd, str, size) == -1) // Read all the file return (84); str[size + 1] = 0; // Parse the string to get characters you're looking for while (str[++i]) { printf("%c", str[i]); if (str[i + 1]) { printf("%c", str[i + 1]); if (str[i + 2]) printf("%c", str[i + 2]); } printf("\n"); } free(str); return (0); } 

我的文件就像: 123456789ABCDEFGHIJKL

这是我的输出:

 123 234 345 456 567 678 789 89A 9AB ABC BCD CDE DEF EFG FGH GHI HIJ IJK JKL KL L 

这是你在找什么?

像这样

 #include  #include  #include  #include  #define BUFFER_SIZE 3 #define MAX_WORDS 100 int main(int argc, char const *argv[]) { char *array[MAX_WORDS]; char buffer[BUFFER_SIZE]; int buf_pos = 0; FILE *fp = stdin; int word_count = 0; int ch; while(word_count < MAX_WORDS && (ch = fgetc(fp)) != EOF){ if(isspace(ch)) continue;//skip whitespaces buffer[buf_pos++ % BUFFER_SIZE] = ch; if(buf_pos >= BUFFER_SIZE){ array[word_count] = calloc(1, sizeof(BUFFER_SIZE+1));//check omitted for(int i = 0; i < BUFFER_SIZE; ++i){ array[word_count][i] = buffer[(buf_pos+i) % BUFFER_SIZE]; } ++word_count; } } if(0 < buf_pos && buf_pos < BUFFER_SIZE){//if not fill buffer array[0] = malloc(sizeof(BUFFER_SIZE+1));//The size was made constant memcpy(array[0], buffer, buf_pos); array[word_count++][buf_pos] = 0; } fclose(fp); for(int i = 0; i < word_count; ++i){ printf("%s\n", array[i]); free(array[i]); } return 0; }