C-将txt读入txt文件 [英] C-Read txt into txt file
问题描述
我在目录"/user/doc"中有一个txt文档test.txt,如下所示:
I have a txt document test.txt in directory "/user/doc" like this:
10 21 34 45 29 38 28
29 47 28 32 31 29 20 12 24
*两行数字用空格"分隔.
*Two lines of numbers separated by "space".
我想将数字写入具有灵活长度的2行数组中.长度可能取决于txt文档的一行中更多数字的数量.在示例中,该值应为9.
I want to write the numbers into a 2-row array, with flexible length. The length may depends on the amount of more numbers in one line of the txt document. In the example it should be 9.
然后,该数组可能如下所示:
And after that the array may look like:
10 21 34 45 29 38 28 0 0
29 47 28 32 31 29 20 12 24
第1行中的数字在数组的第1行中.第2行中的数字位于数组的第2行中.
Numbers in line-1 are in row-1 in the array. And numbers in line-2 are in row-2 in the array.
我得到了下面的代码来一个接一个地填充数组,但是我不知道如何将其修改为所需的内容.有人可以帮忙吗?谢谢!
I got the code below to fill the array one by one but I don't know how to modify it to what I need. Can anybody help? Thanks!
FILE *fp;
int key1[2][10];
if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL)
{
printf("\nCannot open file");
exit(1);
}
else
{
while(!feof(fp))
{
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 10 ;j++)
{
fscanf(fp, "%d", &key1[i][j]);
}
}
}
}
fclose(fp);
推荐答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getColCount(FILE *fin){
long fpos = ftell(fin);
int count = 0;
char buff[BUFSIZ];
while(fgets(buff, sizeof(buff), fin)){
char *p;
for(p=strtok(buff, " \t\n");p;p=strtok(NULL, " \t\n"))
++count;
if(count)break;
}
fseek(fin, fpos, SEEK_SET);
return count;
}
int main(void){
FILE *fp;
int *key1[2];
if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL){
printf("\nCannot open file");
exit(1);
}
for(int i = 0; i < 2; ++i){
int size = getColCount(fp);
key1[i] = malloc((size+1)*sizeof(int));
if(key1[i]){
key1[i][0] = size;//length store top of row
} else {
fprintf(stderr, "It was not possible to secure the memory.\n");
exit(2);
}
for(int j = 1; j <= size ;++j){
fscanf(fp, "%d", &key1[i][j]);
}
}
fclose(fp);
{//check print and dealocate
for(int i = 0; i < 2 ; ++i){
for(int j = 1; j <= key1[i][0]; ++j)
printf("%d ", key1[i][j]);
printf("\n");
free(key1[i]);
}
}
return 0;
}
这篇关于C-将txt读入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!