如何从文件中读取并解析

发布于 2025-01-23 02:36:57 字数 779 浏览 2 评论 0原文

我有一个文件.txt包含一些格式的值:

0,30,25,10

现在,我打开文件并将其存储到一个数组中

char imposta_tratt[300]; 
FILE *fp;
fp = fopen("/home/pi/Documents/imposta_trattamento.txt", "r");
if (fp == 0) return;
fread(imposta_tratt, sizeof(imposta_tratt), 1, fp);
fclose(fp);

,现在我希望将数组填充有我的数据。我的值由隔开,因此我继续对其进行解析:

const char delim[2] = ",";
int t=0;
char *token = strtok(imposta_tratt, delim);
    while (token!=NULL){
    
        strcpy(tratt[t],token);
        token = strtok(NULL, delim);
        tratt[t]=token;
        t++;
    }

在这里,参考文件.txt中的内容,我希望有tratt [0] = 0; Tratt [1] = 30; tratt [2] = 25;等等,但似乎我缺少某些东西,因为它不是这样。

我想要的是将存储在单个变量中的TXT文件的值。有人可以帮忙吗?

I have a file .txt containing some values formatted like this:

0,30,25,10

Now, I open up the file and store it into an array

char imposta_tratt[300]; 
FILE *fp;
fp = fopen("/home/pi/Documents/imposta_trattamento.txt", "r");
if (fp == 0) return;
fread(imposta_tratt, sizeof(imposta_tratt), 1, fp);
fclose(fp);

Now I expect to have the array filled with my data. I have the values separated by a , so I go on and parse it:

const char delim[2] = ",";
int t=0;
char *token = strtok(imposta_tratt, delim);
    while (token!=NULL){
    
        strcpy(tratt[t],token);
        token = strtok(NULL, delim);
        tratt[t]=token;
        t++;
    }

Here, referring to what's in the file .txt, I expect to have tratt[0]=0; tratt[1]=30; tratt[2]=25; and so on, but seems like I am missing something since it's not like this.

All I want is to have the values of the txt file stored in single variables. Can someone help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨落□心尘 2025-01-30 02:36:57

您要实现的目标可以简单地使用fgets()

bool read_file_content(const char *filename, const size_t tsizemax, int tratt[tsizemax], size_t *tsize, const char *delim)
{
    // Attempt to open filename.
    FILE *fp = fopen(filename, "r");
    if (!fp) return false; // Return false upon failure.
    
    // Try to read one line. If you have more, you need a while loop.
    char imposta_tratt[300];
    if (!fgets(imposta_tratt, sizeof imposta_tratt, fp)) {
        fclose(fp);
        return false;
    }
    
    *tsize = 0;
    char tmp[300]; // Temporary buffer. Used for conversion into int.
    char *token = strtok(imposta_tratt, delim);
    
    while (token && *tsize < tsizemax) {
        strncpy(tmp, token, sizeof tmp);
        tratt[(*tsize)++] = atoi(tmp);
        
        token = strtok(NULL, delim);
    }
    
    fclose(fp);
    return true;
}
  • const char *fileName:您要解析的文件。
  • const size_t tsizemaxtratt数组的最大大小。控制大小很重要,否则您的代码将具有缓冲区溢出(例如,例如,您的文件何时具有100多个令牌)。
  • int tratt [tsizemax]:将保持值的数组。
  • size_t *tsize:代币的读数(用于tsizemax的组合)。
  • const char *delim:在您的情况下,定界符a

这是您的main()

int main(void)
{
    int tratt[100];
    size_t size = 0;
    
    if (!read_file_content("in.txt", 100, tratt, &size, ",")) {
        puts("Failed");
        return 1;
    }
    
    for (size_t i = 0; i < size; ++i)
        printf("%d\n", tratt[i]);
}

输出:

0
30
25
10

What you are trying to achieve can simply be done using fgets():

bool read_file_content(const char *filename, const size_t tsizemax, int tratt[tsizemax], size_t *tsize, const char *delim)
{
    // Attempt to open filename.
    FILE *fp = fopen(filename, "r");
    if (!fp) return false; // Return false upon failure.
    
    // Try to read one line. If you have more, you need a while loop.
    char imposta_tratt[300];
    if (!fgets(imposta_tratt, sizeof imposta_tratt, fp)) {
        fclose(fp);
        return false;
    }
    
    *tsize = 0;
    char tmp[300]; // Temporary buffer. Used for conversion into int.
    char *token = strtok(imposta_tratt, delim);
    
    while (token && *tsize < tsizemax) {
        strncpy(tmp, token, sizeof tmp);
        tratt[(*tsize)++] = atoi(tmp);
        
        token = strtok(NULL, delim);
    }
    
    fclose(fp);
    return true;
}
  • const char *filename: The file you want to parse.
  • const size_t tsizemax: The maximum size of your tratt array. It is important to control the size, otherwise your code will have buffer overflow (think of when your file has more than 100 tokens, for example).
  • int tratt[tsizemax]: The array that will hold the values.
  • size_t *tsize: The number of tokens read (used in combination of tsizemax).
  • const char *delim: The delimiter(s), in your case a ,.

This is your main():

int main(void)
{
    int tratt[100];
    size_t size = 0;
    
    if (!read_file_content("in.txt", 100, tratt, &size, ",")) {
        puts("Failed");
        return 1;
    }
    
    for (size_t i = 0; i < size; ++i)
        printf("%d\n", tratt[i]);
}

Output:

0
30
25
10
野の 2025-01-30 02:36:57

假设“ in.txt”具有

0,30,25,10

以下程序使用fscanf将整数读取到tratt阵列中,一对一。当我们使用fscanf读取整数时,我们确保其返回值如预期。如果没有,我们关闭文件并退出。如果fscanf的返回值不如预期,则该程序还会打印出哪种错误类型。当前,如果发生任何错误,程序将停止。但是,您可以根据愿意的错误,使程序行为不同。

随着输出,程序将所有整数读取到tratt数组中。 现在,输出是

0
30
25
10

该程序假设我们知道要阅读到tratt的元素数量。如果不这样记录有关该文件的信息,例如文件中的数字数量和数据类型(最适合二进制文件)。这些只是几种可能性。

一种更好的方法可能是读取字符(例如,使用getc),然后使用strtol将字符数字序列转换为long int(我会采取类似的方法)。

然而,这种方法更简洁,应该足够。

#include <stdio.h>
#include <stdlib.h>

#define FILE_NAME "in.txt"
#define MAX_LEN 4

int main(void) {

    int i, tratt[MAX_LEN];
    FILE *fp = fopen(FILE_NAME, "r");      /* open file for reading */

    /* if cannot open file */
    if (fp == NULL) {

        printf("Cannot open %s\n", FILE_NAME);
        exit(EXIT_FAILURE);

    }

    /* read integer, checking return value of scanf as expected */
    if (fscanf(fp, "%d", &tratt[0]) != 1) {
        if (ferror(fp))
            printf("fscanf: read error\n");
        else if (feof(fp))
            printf("fscanf: end of file\n");
        else
            printf("fscanf: matching failure\n");

        fclose(fp);
        exit(EXIT_FAILURE);
    }

    for (i = 1; i < MAX_LEN; i++)
        /* read comma plus integer, checking return value of scanf */
        if (fscanf(fp, ",%d", &tratt[i]) != 1) {
            if (ferror(fp))
                printf("fscanf: read error\n");
            else if (feof(fp))
                printf("fscanf: end of file\n");
            else
                printf("fscanf: matching failure\n");

            fclose(fp);
            exit(EXIT_FAILURE);

        }
    fclose(fp);    /* close file */

    /* print integers stored in tratt */
    for (i = 0; i < MAX_LEN; i++)
        printf("%d\n", tratt[i]);

    return 0;

}

Suppose "in.txt" has contents

0,30,25,10

The below program uses fscanf to read the integers into the tratt array, one-by-one. As we read integers using fscanf, we make sure it's return value is as expected. If not, we close the file and exit. In the event that the return value of fscanf is not as expected, the program also prints which type of error occurred. Currently, if any error occurs, the program stops. However, you can make the program behave differently depending on the error that occurred if you like.

As output, the program prints all of the integers read into the tratt array. The output is

0
30
25
10

Now this program assumes we know the number of elements we want to read into tratt. If we do not, we could allow for dynamically allocating more memory should the array need more elements or perhaps "in.txt" could contain a data structure, say, at the beginning/end of the file that records information about the file, such as the number of numbers in the file and the data type (a binary file would be best suited for this). These are just a couple of the possibilities.

A better approach might be to read characters in one-by-one (say, using getc) and use strtol to convert a sequence of character digits to a long int (I would have taken an approach similar to this).

Nevertheless, this approach is more succinct and should suffice.

#include <stdio.h>
#include <stdlib.h>

#define FILE_NAME "in.txt"
#define MAX_LEN 4

int main(void) {

    int i, tratt[MAX_LEN];
    FILE *fp = fopen(FILE_NAME, "r");      /* open file for reading */

    /* if cannot open file */
    if (fp == NULL) {

        printf("Cannot open %s\n", FILE_NAME);
        exit(EXIT_FAILURE);

    }

    /* read integer, checking return value of scanf as expected */
    if (fscanf(fp, "%d", &tratt[0]) != 1) {
        if (ferror(fp))
            printf("fscanf: read error\n");
        else if (feof(fp))
            printf("fscanf: end of file\n");
        else
            printf("fscanf: matching failure\n");

        fclose(fp);
        exit(EXIT_FAILURE);
    }

    for (i = 1; i < MAX_LEN; i++)
        /* read comma plus integer, checking return value of scanf */
        if (fscanf(fp, ",%d", &tratt[i]) != 1) {
            if (ferror(fp))
                printf("fscanf: read error\n");
            else if (feof(fp))
                printf("fscanf: end of file\n");
            else
                printf("fscanf: matching failure\n");

            fclose(fp);
            exit(EXIT_FAILURE);

        }
    fclose(fp);    /* close file */

    /* print integers stored in tratt */
    for (i = 0; i < MAX_LEN; i++)
        printf("%d\n", tratt[i]);

    return 0;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文