【问题标题】:how to read and write from .dat file in verifone如何在verifone中读取和写入.dat文件
【发布时间】:2015-08-02 06:51:53
【问题描述】:

我想在 verifone 中读取和写入文本或 .dat 文件以在其上存储数据。 我怎样才能做到? 这是我的代码

int main()
{
  char buf [255];
  FILE *tst;
  int dsply = open(DEV_CONSOLE , 0);
  tst = fopen("test.txt","r+");
  fputs("this text should write in file.",tst);
  fgets(buf,30,tst);

  write(dsply,buf,strlen(buf));
  return 0;
}

【问题讨论】:

  • 您很少需要同时读取和写入文件,因此在您熟悉文件 I/O 之前不要使用+ 模式。相反,使用"w" 打开文件,写入,关闭它。然后用"r" 再次打开它,读取并关闭它。养成检查错误条件的返回值并将每个 fopen 与相应的 fclose 配对的习惯。
  • 如何在该文件中搜索?通过哪个命令?
  • 完全不清楚你想要什么。我猜你关于阅读和写作的问题是错误的。 (如果你想有一个类似数据库的结构,把它加载到内存中,对内存中的数据库进行操作,然后再次提交到文件中。无论如何,请阅读 C 中文件 I/O 的好教程。)跨度>

标签: c point-of-sale verifone


【解决方案1】:

“Vx 解决方案程序员手册”(“23230_Verix_V_Operating_System_Programmers_Manual.pdf”)的第 3 章是关于文件管理的,包含我在终端上处理数据文件时通常使用的所有功能。通读一遍,我想你会找到你需要的一切。

为了让您开始,您需要将open() 与您想要的标志一起使用

  • O_RDONLY(只读)
  • O_WRONLY(只写)
  • O_RDWR(读写)
  • O_APPEND(以文件末尾的文件位置指针打开)
  • O_CREAT(如果文件不存在则创建),
  • O_TRUNC(如果文件已经存在,则截断/删除之前的内容),
  • O_EXCL(如果文件已经存在则返回错误值)

成功时,open 将返回一个正整数,它是一个句柄,可用于后续访问文件。失败时返回-1;

文件打开后,您可以使用read()write() 来操作内容。

当你处理完文件后,一定要调用close() 并传入 open 的返回值。

你上面的例子看起来像这样:

int main()
{
  char buf [255];
  int tst;
  int dsply = open(DEV_CONSOLE , 0);
  //next we will open the file.  We will want to read and write, so we use
  // O_RDWR.  If the files does not already exist, we want to create it, so
  // we use O_CREAT.  If the file *DOES* already exist, we want to truncate
  // and start fresh, so we delete all previous contents with O_TRUNC
  tst = open("test.txt", O_RDWR | O_CREAT | O_TRUNC);

  // always check the return value.
  if(tst < 0)
  {
     write(dsply, "ERROR!", 6);
     return 0;
  }
  strcpy(buf, "this text should write in file.")
  write(tst, buf, strlen(buf));
  memset(buf, 0, sizeof(buf));
  read(tst, buf, 30);
  //be sure to close when you are done
  close(tst);

  write(dsply,buf,strlen(buf));
  //you'll want to close your devices, as well
  close(dsply);
  return 0;
}

您的 cmets 也会询问搜索。为此,您还需要将lseek 与以下指定起点之一一起使用:

  • SEEK_SET — 文件开头
  • SEEK_CUR — 当前查找指针位置
  • SEEK_END — 文件结束

例子

SomeDataStruct myData;
...
//assume "curPosition" is set to the beginning of the next data structure I want to read
lseek(file, curPosition, SEEK_SET);
result = read(file, (char*)&myData, sizeof(SomeDataStruct));
curPosition += sizeof(SomeDataStruct);
//now "curPosition" is ready to pull out the next data structure.

请注意,内部文件指针已经位于“curPosition”,但是这样做可以让我在操作那里的内容时随意向前和向后移动。因此,例如,如果我想回到以前的数据结构,我只需将“curPosition”设置如下:

curPosition -= 2 * sizeof(SomeDataStruct);

如果我不想跟踪“curPosition”,我还可以执行以下操作,这也会将内部文件指针移动到正确的位置:

lseek(file, - (2 * sizeof(SomeDataStruct)), SEEK_CUR);

您可以选择最适合您的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多