繁体   English   中英

从文件中读取多行数据

[英]Reading multiple lines of data from a file

我正在从预读的文件中读取数据,并将其存储在缓冲区中,在该缓冲区中,我遍历了一个结构以组织数据,然后将其重新保存在另一个文件中。

但是我只读一行代码。

我的代码-打开文件:

File *p_file

char fileLocation[40];
char buff[1000];

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

p_file = fopen(fileLocation, "r");

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

循环读取数据并保存文件

while(fgets(buff, 1000, p_file)!=NULL
{
    printf("%s", buff);

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

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

 if ((p_file = fopen(fileLocation, "w")) == NULL
 {
    puts("\n Could not point to the file.");
 }else{
    printf("\nSaving");
    fprintf(p_file, "%04d:%04d:%04d:%04:%s \n",
            storedData.source,
            storedData.destination,
            storedData.type,
            storedData.port,
            storedData.data );

    fclose(p_file);
 }
fclose(p_file);

当前数据输出:

0001:0002:0003:0021:CLS

想要的数据输出:

0001:0002:0003:0021:CLS
0001:0010:0003:0021:CLS
0001:0002:0002:0080:<HTML>

我相信我必须声明一个整数值以用于遍历文件内容以及使用malloc来获取结构的大小,但是我不知道该怎么做。 任何帮助都感激不尽。

您正在过度使用p_file来读取文件和写入文件。

if ((p_file = fopen(fileLocation, "w")) == NULL)

这样,您就失去了打开阅读文件的指针。 当您在else部分中关闭它时, fgets()认为不再有任何行。

使用其他一些变量来写入文件。


如果要处理缓冲的数据,请更改while(fgets()...以读取所有行,然后在每一行上工作fgets()不会读取多行。

你的循环实际上只做一次

storedData.data = strtok(0, ":\\n");

所以你只要走第一行。

FILE *in_file;
FILE *out_file;
char fileLocation[40];
char buff[1000];

printf("\nEnter file name: \n");
if( 1 != scanf(" %s, fileLocation) )
{
    perror( " scanf failed for input file: );
    exit( EXIT_FAILURE );
}

if( NULL == (in_file = fopen(fileLocation, "r") )
{
    perror( "fopen failed for input file" );
    exit( EXIT_FAILURE );
}

printf("\nEnter a File Name to save:");
if( 1 != scanf(" %s", fileLocation) )
{
    perror( "scanf failed for outut file name" );
    fclose( in_file ); // cleanup
    exit( EXIT_FAILURE );
}

if ( NULL == (out_file = fopen(fileLocation, "w")) )
{
    perror( " fopen failed for output file" );
    fclose( in_file ); // cleanup
    exit( EXIT_FAILURE )l
}

while(fgets(buff, 1000, p_file)!=NULL) )
{
    printf("%s", buff);

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

    printf("\nSaving");
    fprintf(p_file, "%04d:%04d:%04d:%04:%s \n",
        storedData.source,
        storedData.destination,
        storedData.type,
        storedData.port,
        storedData.data );
} // end while

fclose( in_file );  // cleanup
fclose( out_file ); // cleanup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM