【问题标题】:How do you split a string read from a file into arrays in C如何将从文件中读取的字符串拆分为 C 中的数组
【发布时间】:2012-05-09 17:21:44
【问题描述】:

我有一个简单的文件,其中包含 100 个文件名及其相应大小的列表,如下所示:

file1.txt, 4000
file2.txt, 5000

等等。 如何逐行读取文件,然后将文件名列表存储到 char 数组中,然后将大小列表存储到 int 数组中?我正在尝试像这样使用 sscanf ,但这不起作用。我遇到了段错误:

main(){
    char line[30];
    char names[100][20];
    int sizes[100];
    FILE *fp;
    fp = fopen("filelist.txt", "rt");
    if(fp == NULL){
        printf("Cannot open filelist.txt\n");
        return;
    }

    while(fgets(line, sizeof(line), fp) != NULL){
        sscanf(line, "%s, %d", names[i][0], sizes[i]);
        printf("%d", sizes[i]);
        i++;
    }
}

【问题讨论】:

标签: c arrays file


【解决方案1】:

i不被阻止超过100,这是可以读取的sizesnames的最大数量。如果文件中有超过一百行,则会发生越界访问。通过进行此(或类似)更改来防止这种情况发生:

while (i < 100 & fgets(line, sizeof(line), fp) != NULL) {

【讨论】:

  • @IlanaMannine,你改变了什么?
【解决方案2】:
#include <stdio.h>
int main()
{
char line[30];
char names[100][20];
int sizes[100];
int i = 0;
FILE *fp;

fp = fopen("1.txt", "rt");

if(fp == NULL)
{
    printf("cannot open file\n");
    return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
     sscanf(line, "%[^,]", names[i]);//output the string until the char is the ","
     sscanf(line, "%*s%s", sizes);//skip the characters and get the size of the file 
        printf("%s\n", names[i]);
        printf("%s\n", sizes);

    i++;
}
fclose(fp);


return 0;
}

我想这就是你想要的。

你应该正确理解 sscanf()。

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2022-01-18
    • 2017-02-02
    相关资源
    最近更新 更多