1

我应该创建一个程序,该程序采用给定的文件并创建一个带有反向 txt 的文件。我想知道如果我不知道文件的确切大小,是否可以从文件末尾开始 read() 并将其复制到创建文件的第一个字节?我也用谷歌搜索过这个,遇到了很多关于 fread、fopen 等的例子。但是我不能在这个项目中使用这些,我只能使用 read、open、lseek、write 和 close。这是我的代码,到目前为止它并不多,但仅供参考:

#include<stdio.h>
#include<unistd.h>

int main (int argc, char *argv[])
{
    if(argc != 2)/*argc should be 2 for correct execution*/
    {
        printf("usage: %s filename",argv[0[]);}
    }
    else
    {
    int file1 = open(argv[1], O_RDWR);
    if(file1 == -1){
    printf("\nfailed to open file.");
        return 1;
    } 
    int reversefile = open(argv[2], O_RDWR | O_CREAT);

    int size = lseek(argv[1],    0, SEEK_END);
    char *file2[size+1];
    int count=size;
    int i = 0

    while(read(file1, file2[count], 0) != 0)
    {
      file2[i]=*read(file1, file2[count], 0);
      write(reversefile, file2[i], size+1);
      count--;
      i++;
      lseek(argv[2], i, SEEK_SET);
   }
4

3 回答 3

1

我怀疑大多数文件系统是否旨在有效地支持此操作。很有可能,您必须阅读整个文件才能读完。出于同样的原因,大多数语言可能不包含任何用于向后读取文件的特殊功能。

只是想出一些东西。尝试读取内存中的整个文件。如果它太大,将开头转储到一个临时文件中并继续阅读......最后将所有临时文件合并为一个。此外,您可以通过手动低级操作磁盘扇区或至少直接针对文件系统进行低级编程来做一些聪明的事情。不过,看起来这不是你想要的。

于 2013-10-11T19:41:43.127 回答
0

这没有错误检查==真的很糟糕

  1. 使用 stat 获取文件大小
  2. 使用 malloc 创建缓冲区
  3. 将文件读入缓冲区
  4. 设置指向文件末尾的指针
  5. 通过缓冲区向后打印每个字符。

如果你用谷歌有创意,你可以得到几个这样的例子。IMO 到目前为止,您获得的帮助并不是很好的提示。这似乎是功课,所以要小心抄袭。阅读有关此处使用的调用的信息。stat (fstat) fread(读取)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
   struct stat st;
   char *buf;
   char *p;
   FILE *in=fopen(argv[1],"r");   
   fstat(fileno(in), &st);         // get file size in bytes
   buf=malloc(st.st_size +2);      // buffer for file
   memset(buf, 0x0, st.st_size +2 );
   fread(buf, st.st_size, 1, in);  // fill the buffer
   p=buf;
   for(p+=st.st_size;p>=buf; p--)  // print traversing backwards
      printf("%c", *p);
   fclose(in);   
   return 0;
}
于 2013-10-11T20:11:40.690 回答
0

为什么不尝试fseek在文件中导航?这个函数包含在 中stdio.h,就像fopen和一样fclose

另一个想法是实现一个简单的堆栈......

于 2013-10-11T19:39:33.597 回答