簡體   English   中英

C將txt讀入txt文件

[英]C-Read txt into txt file

我在目錄“ / user / doc”中有一個txt文檔test.txt,如下所示:

10 21 34 45 29 38 28
29 47 28 32 31 29 20 12 24

*兩行數字用“空格”分隔。

我想將數字寫入具有靈活長度的2行數組中。 長度可能取決於txt文檔一行中更多數字的數量。 在示例中,它應該為9。

然后,該數組可能如下所示:

10 21 34 45 29 38 28 0 0
29 47 28 32 31 29 20 12 24

第1行中的數字位於數組的第1行中。 第2行中的數字位於數組的第2行中。

我得到了下面的代碼來一個接一個地填充數組,但我不知道如何將其修改為所需的內容。 有人可以幫忙嗎? 謝謝!

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);

使用fgets逐行閱讀每一行,然后使用strtok對其進行拆分,並使用strtol解析。

像這樣:

char line[256];
int l = 0;
while (fgets(line, sizeof(line), input_file))
{
    int n = 0;

    for (char *ptr = strtok(line, " "); ptr != NULL; ptr = strtok(NULL, " "))
    {
        key1[l][n++] = strtol(ptr, NULL, 10);
    }

    l++;
}
#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM