我想做的是我有一些 C 代码可以翻译字母数组及其频率数组,我现在尝试读取一个文件并将文件的行号转换为匹配的 ASCII 代码(第 32 行将转换为 ASCII 代码 32)并获取该行的内容。我是 C 语言新手,还没有探索过获取文件,本质上我可以使用一些技巧。
- 加载文件
- 逐行读取文件并将数字内容分配给数组
- 抓取 # 行,然后将其转换为匹配的 ASCII 代码。
如果需要,我可以发布我的代码,但我对抓取文件作为我的输入感到更加困惑。
int main(int argc, char* argv[])
{
char arr[127];
int freq[127];
int num_of_line = 127;
int size = sizeof(arr) / sizeof(arr[0]);
FILE *fp = fopen("kjvdist.txt","r");
if(fp == NULL){
printf("The File Does not exist, Try Again?\n");
return;
}
char *ptr[num_of_line];
for(int row = 0; row < num_of_line; row++) {
ptr[row] = malloc(size);/*allocate memory */
fgets(ptr[row],sizeof(ptr[row]),fp);
int index = ptr[row];
char asc = ptr[row];
arr[index] = asc; /* do operation here on ptr[row] to get equivalent ASCII code */
for(int col = 0; ptr[row][col] ;col++) {
if(ptr[row][col]>='0' && ptr[row][col]<='9')//check for alphabets & other also
int ascii = ptr[row][col] + 48;
/* something like above you need to do */
}
}
HuffmanCodes(arr, freq, size);
return 0;
}
最佳答案
如果您希望读取的文件不大,最简单的解决方案可能是将整个文件读入内存。您可以使用 mmap()
或自行执行以下操作:
fd = open(filename, O_RDONLY, 0);
fstat(fd, &st);
data = malloc(st.st_size + 1);
read(fd, data, st.st_size);
data[st.st_size] = '\0';
close(fd);
然后在数组data
中查找换行符(错误检查留给读者作为练习)。
lineno = 0;
line = data;
while ((nl = strchr(line, '\n') != NULL) {
*nl = '\0';
process(line, ++lineno);
line = nl + 1;
}
关于c - 在C中逐行读取文件,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839812/