正在读取文件,但未保存

时间:2014-12-11 17:52:51

标签: c function struct

我目前正在编写一个程序来读取文件,然后将读取的信息保存到新文件中。但是,在写入第二个文件时,不会保存任何数据。

我正在使用结构来帮助分解我想要使用的文本文件

struct file{
    int source;
    int destination;
    int type;
    int port;
    char data[50];
};

阅读完文件后,我创建了一个分解数据并将其打印到屏幕的功能

int parseFile(int countData, struct file *storedData)
{
    FILE *in_File;

    char buff[1000];


    while(fgets(buff, 1000, in_File)!=NULL)
    {

        printf("%s", buff);

        storedData[countData].source = atoi(strtok(buff, ":"));
        storedData[countData].destination = atoi(strtok(0, ":"));
        storedData[countData].type = atoi(strtok(0, ":"));
        storedData[countData].port = atoi(strtok(0, ":"));
        strcpy(storedData[countData].data, strtok(0, ":\n") );
    }
}

最后我创建了一个保存文件的函数

void saveFile(int countData, struct file *storedData)
{
    FILE *in_File;

    char fileLocation[40];
    int i = 0;

    printf("\nEnter a File Name to save:");
    scanf("%s", fileLocation);

    if ((in_File = fopen(fileLocation, "w")) == NULL){
        puts(" \n Could not point to the file.");
    }else{
        for(i=0;i<countData;i++)
        {
            fprintf(in_File, "%04d:%04d:%04d:%04d:%s \n",
                    storedData[i].source,
                    storedData[i].destination,
                    storedData[i].type,
                    storedData[i].port,
                    storedData[i].data );
        }
    }
        fclose(in_File);
}

在main函数中,我使用malloc来分配struct的大小

int main()
{
    struct file *storedData;
    storedData = malloc(sizeof(struct file));

    int countData = 0;

    banner();
    readFile(countData, storedData);
    parseFile(countData, storedData);
    saveFile(countData, storedData);

    return 0;
}

获取数据并通过我的parseFile函数运行时,每行都会逐行写出来

数据输出示例:

0001:0002:0003:0021:CLS 
0003:0004:0002:0180:100000000000000000030
0006:0003:0002:0041:100000000000000000019
0006:0002:0002:0060:100000000000000000020

然而,当保存到文件时,没有存储此输出,我想知道我可以做些什么来解决它

编辑:

这是readFile函数:

void readFile(int countData, struct file *storedData)
{
    FILE *in_File;

    char fileLocation[40];

    printf("\nEnter file name: \n");
    scanf("%s", fileLocation);

    in_File = fopen(fileLocation, "r");

    if(!in_File)
    {
        printf("\nError!\n");
    }
}

1 个答案:

答案 0 :(得分:3)

storedData = malloc(sizeof(struct file));

为一个文件记录分配足够的内容。

您的例程parseFile()将重复写入该记录,但由于它永远不会递增countData,因此它不会写任何内容 - 尽管它确实如此,但父例程将不会收到更新的countData ,因为您必须通过int * &countDataparseFile()例程递增它。

由于for(i=0;i<countData;i++)存在,您甚至从未读过一行,因为0 < 0为假。

如果您进行了更改,只要您点击第二条记录,就会覆盖内存和coredump,因为您只在main()

中分配了一个空间的记录空间

同样在parseFile()中,您必须在阅读之前打开文件!类似的东西:

in_File = fopen(inputFileName, "r");

[edit]我看到你用readFile()更新了 - 它需要返回打开的FILE *供parseFile使用,你需要将那个FILE *传递给parseFile才能使用。

相关问题