C++从文件读取代码存入字符数组
时间: 2024-04-17 17:05:58 浏览: 87
以下是从文件读取代码存入字符数组的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char filename[100], ch;
int i = 0, size;
printf("Enter the filename: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file\n");
exit(1);
}
fseek(fp, 0, SEEK_END); // move file pointer to end of file
size = ftell(fp); // get file size
fseek(fp, 0, SEEK_SET); // move file pointer to beginning of file
char *code = (char*)malloc(size * sizeof(char)); // allocate memory for code array
while ((ch = fgetc(fp)) != EOF) {
code[i] = ch; // read character from file and store in code array
i++;
}
code[i] = '\0'; // terminate code array with null character
printf("Code read from file:\n%s\n", code);
fclose(fp);
free(code); // free memory allocated for code array
return 0;
}
```
这个程序要求用户输入文件名,然后打开文件并读取其中的代码,将其存储在动态分配的字符数组中,最后输出该数组中的内容。程序使用了 fseek 和 ftell 函数来获取文件大小,然后动态分配了一个足够大的字符数组来存储文件内容。最后,程序释放了动态分配的内存。
阅读全文