C ++:低级文件操作

时间:2016-02-23 20:30:28

标签: c++ file-io

我尝试理解C中的文件操作。

我的目标是将一些值写入一个名为file1.dbs的二进制文件中,然后读取这些值并将它们正确地写入一个名为file2.txt的文本文件中。

在下面的代码中,我正在创建一个struct product1。然后是二进制文件 fn1 ,并在其中写入struct product p1。

最后我创建了file2.txt(FILE * f ),有权写入,读取fn1文件的值,将它们存储在新的struct p2中,并尝试将这些值写入f stream通过fprintf()。

我在Windows 10上编译了程序,这是运行时的输出:

在file2.txt上输出 产品名称:(这是一个奇怪的符号,甚至无法复制)

供应商:

价格:5110744

#include "stdio.h"
#include <iostream>
#include "io.h"
#include "process.h"
#include "string.h"
#include "fcntl.h"
#define file1 "file1.dbs"
#define file2 "file2.txt"


struct product{
    char name[70];
    char supplier[70];
    int price;
};

FILE *f;
int fn1;

int main(){
    fn1=_open(file1, _O_CREAT|_O_RDWR);
    if(fn1==-1){
        printf("file1.dbs could not be created\n");
    }else{
        printf("file1.dbs created succesfully\n");
    }

    product p1;
    strcpy(p1.name, "Gameboy");
    strcpy(p1.supplier, "Gamestore");
    p1.price=15;
    write(fn1, &p1, sizeof product);
    product p2;
    f=fopen(file2, "w");
    read(fn1, &p2, sizeof product);
    fprintf(f,"Profuct name:%s\nSupplier:%s\nPrice:%d", p2.name, p2.supplier, p2.price);
    close(fn1);
    fclose(f);
    printf("Done!\n");

    return 0;
}

我错过了一些明显的东西吗? 我相信那个特定的例子我不需要使用lseek来重新定位file1.dbs文件的偏移量,因为我只写了一个结构。感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

 read(fn1, &p2, sizeof product);
       ^

这里使用的是在读/写模式下打开的相同文件描述符。但是在write当前偏移量将在结构之后,您应该通过lseek将其重新定位到开头。

其实你喜欢

file.dbs 
         ^
write(...)
file.dbs struct_data
                    ^
read(...)
file.dbs struct_data????????
                            ^
相关问题