读取和写入不同的值

发布于 2024-12-10 11:49:58 字数 367 浏览 1 评论 0原文

大家好,这基本上是我上一个问题的延伸。我已经在文件中写入了短整型值,使用

short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );

它工作正常,但是当我尝试检索这样的值时,

short int y ;
fread(&y , 2, 1 ,f1);
printf("%d"  , y);

它给了我答案 8180,下次是 12276 等等...我实际上应该做什么

我想在我的文件中存储短整数然后一一检索它们我做错了吗请指导我

Hello every one this is basically extension to my previous question. i have write the short int value in file using

short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );

it working fine but when i tried to retrieve value like this

short int y ;
fread(&y , 2, 1 ,f1);
printf("%d"  , y);

it gave me answer 8180 and next time 12276 so on... what should i do

actually I want to store short integers in my file and then retrieve them one by one am i doing it wrong kindly guide me

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

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

发布评论

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

评论(3

天涯离梦残月幽梦 2024-12-17 11:49:58

最有可能的是,您没有在写入和读取之间关闭并重新打开文件。我建议创建一个执行这两个操作的小函数,首先写入,然后关闭和刷新,然后读取。看看你会得到什么样的结果。另外,请确保您使用的是二进制模式。

Most likey you aren't closing and reopening the file between writing and reading. I would suggest creating a small function that does both actions, first writing, then closing and flushing, then reading. See what kind of results you get with that. Also, make sure you are using binary mode.

小猫一只 2024-12-17 11:49:58

如果您想从刚刚写入的文件中读回,则需要使用“w+”选项打开它以允许读取和写入。然后,您需要返回到文件的开头:

// Open the file
const char* fname = "infile";
FILE * f1 = fopen("infile" ,"wb+");
if( f1 != NULL )
{
    printf("opened file '%s' for writing / reading\n", fname);

    // Write two bytes
    short int x = 254;
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1 );
    printf("%hd bytes written\n"  , bytes_written);

    // Seek to the start of the file
    int seek_result = fseek(f1, 0, 0);
    if( seek_result == 0 )
    {
        printf("found beginning of file\n");
    }
    else
    {
        printf("failed to seek to beginning of file\n");
    }

    // Read the two bytes back in
    short int y = -9999;
    size_t bytes_read = fread(&y, 1, sizeof(short int), f1);
    printf("%hd bytes read: %hd\n", bytes_read, y);

    // We're done with the file so close it
    fclose(f1);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for writing / reading\n", fname);
}

或者,您可以将读/写作为单独的操作:

// Open the file
const char* fname = "infile";
FILE * f1 = fopen("infile" ,"wb");
if( f1 != NULL )
{
    printf("opened file '%s' for writing\n", fname);

    // Write two bytes
    short int x = 254;
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1 );
    printf("%hd bytes written\n"  , bytes_written);

    // We're done with the file so close it
    fclose(f1);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for writing\n", fname);
}

// re-open the file
FILE * f2 = fopen("infile" ,"rb");
if( f2 != NULL )
{
    printf("opened file '%s' for reading\n", fname);

    // Read the two bytes back in
    short int y = -9999;
    size_t bytes_read = fread(&y, 1, sizeof(short int), f2);
    printf("%hd bytes read: %hd\n", bytes_read, y);

    // We're done with the file so close it
    fclose(f2);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for reading\n", fname);
}

请注意,在原始代码中,您没有检查 fread 的返回值来检查您是否实际上从中读取了任何内容文件。如果您这样做了,您会看到它返回 0 表示它读取了 0 个字节。如果您没有从文件中读取任何内容并且没有初始化y,那么它可能只是一个随机数。

If you want to read back from the file you just wrote to, you need to open it with "w+" options to allow you to read and write. You then need to seek back to the beginning of the file:

// Open the file
const char* fname = "infile";
FILE * f1 = fopen("infile" ,"wb+");
if( f1 != NULL )
{
    printf("opened file '%s' for writing / reading\n", fname);

    // Write two bytes
    short int x = 254;
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1 );
    printf("%hd bytes written\n"  , bytes_written);

    // Seek to the start of the file
    int seek_result = fseek(f1, 0, 0);
    if( seek_result == 0 )
    {
        printf("found beginning of file\n");
    }
    else
    {
        printf("failed to seek to beginning of file\n");
    }

    // Read the two bytes back in
    short int y = -9999;
    size_t bytes_read = fread(&y, 1, sizeof(short int), f1);
    printf("%hd bytes read: %hd\n", bytes_read, y);

    // We're done with the file so close it
    fclose(f1);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for writing / reading\n", fname);
}

Alternatively, you could read / write as separate operations:

// Open the file
const char* fname = "infile";
FILE * f1 = fopen("infile" ,"wb");
if( f1 != NULL )
{
    printf("opened file '%s' for writing\n", fname);

    // Write two bytes
    short int x = 254;
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1 );
    printf("%hd bytes written\n"  , bytes_written);

    // We're done with the file so close it
    fclose(f1);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for writing\n", fname);
}

// re-open the file
FILE * f2 = fopen("infile" ,"rb");
if( f2 != NULL )
{
    printf("opened file '%s' for reading\n", fname);

    // Read the two bytes back in
    short int y = -9999;
    size_t bytes_read = fread(&y, 1, sizeof(short int), f2);
    printf("%hd bytes read: %hd\n", bytes_read, y);

    // We're done with the file so close it
    fclose(f2);
}
else
{
    // Something went wrong and we failed to open the file
    printf("failed to open file '%s' for reading\n", fname);
}

Note that in your original code you weren't checking the return value of fread to check whether you'd actually read anything from the file. If you'd done that you'd have seen it was returning 0 to indicate that it read 0 bytes. If you're not reading anything from the file and you're not initialising y then it's likely to just be a random number.

中性美 2024-12-17 11:49:58

我同意乔恩·凯奇的回答(支持他,而不是我!)

还要注意(很久以前),Windows/DOS 系统需要用“wb”、“rb”而不是“w”和“r”打开二进制文件'。我不确定情况是否仍然如此,但尝试一下是没有问题的。

这里有一些代码可以让事情变得更清楚:

short int x= 254;
int nwritten;
FILE * f1 = fopen("infile" ,"w+b");
nwritten=fwrite (&x , 1 , sizeof(short int ) , f1 ); /* check number of shorts written */
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten);

对于读取部分:

short int y ;
int nread;
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */
if (nread == 1) printf("%d"  , y);
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread);

另外,请记住文件内的位置在每次读/写后都会递增。在阅读之前您可能想回到文件的开头。通过关闭/重新打开文件(如 Jon 答案中所示)或通过使用以下命令开始查找来执行此操作:

fseek(f1,0L,SEEK_SET); /* you also can use rewind(f1); for the same result */

完整代码:

short int x= 254;
int nwritten;
FILE * f1 = fopen("infile" ,"w+b");
nwritten=fwrite (&x , 1 , sizeof(short int ) , f1 ); /* check number of shorts written */
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten);

short int y ;
int nread;
fseek(f1,0L,SEEK_SET); /* get back to the start */
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */
if (nread == 1) printf("%d"  , y);
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread);

I agree with Jon Cage answer (upvote him, not me!)

Also note that (a long time ago), Windows/DOS systems needed binary files to be opened with 'wb', 'rb' instead of 'w' and 'r'. I'm not sure it is still the case, but there's no problem trying.

Here's a bit of code to get things more clear:

short int x= 254;
int nwritten;
FILE * f1 = fopen("infile" ,"w+b");
nwritten=fwrite (&x , 1 , sizeof(short int ) , f1 ); /* check number of shorts written */
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten);

And for the reading part:

short int y ;
int nread;
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */
if (nread == 1) printf("%d"  , y);
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread);

Also, remember that the position inside the file is incremented after each read/write. You might want to get back to the start of the file before reading. Do this either by closing/reopening the file as in Jon answer or by seeking to the start using:

fseek(f1,0L,SEEK_SET); /* you also can use rewind(f1); for the same result */

Full code:

short int x= 254;
int nwritten;
FILE * f1 = fopen("infile" ,"w+b");
nwritten=fwrite (&x , 1 , sizeof(short int ) , f1 ); /* check number of shorts written */
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten);

short int y ;
int nread;
fseek(f1,0L,SEEK_SET); /* get back to the start */
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */
if (nread == 1) printf("%d"  , y);
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文