我在Unix中输入输出有问题

时间:2014-03-20 07:00:11

标签: c unix

我正在尝试编写一些名称并将其保存到“name.txt”文件中,并使列表显示在监视器上。幸运的是,我设法将这些名字保存在“name.txt”中,但不知道如何在监视器上看到它们......  任何帮助将不胜感激..

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define MAX_SIZE 500

int main(void)
{
   int i, fd;
   char nameBuf[MAX_SIZE];

   fd=open("name.txt", O_RDWR|O_CREAT, 0744);
   if(fd<0)
   {
        perror("An error occured while opening the file");
        exit(1);
   }

   while(1)
   {
        puts("Enter name(end to quit) : ");
        read(0, nameBuf, sizeof(nameBuf));

        if( !strncmp(nameBuf, "end", 3) )
        {
                printf("end input\n");
                break;
        }
        write(fd, nameBuf, 7);
   }


   printf("for loop begins...\n");
   for(i=0; i<3; i++)
   {
        fprintf(stdout, nameBuf);
    }

   puts("Operation completed...");

   close(fd);

   return 0;
}

2 个答案:

答案 0 :(得分:1)

希望此代码有所帮助。在需要的地方插入评论。

int main(void)
{
   int i, fd;
   char nameBuf[MAX_SIZE];

   fd=open("name.txt", O_RDWR|O_CREAT, 0744);
   if(fd<0)
   {
        perror("An error occured while opening the file");
        exit(1);
   }

   while(1)
   {
        puts("Enter name(end to quit) : ");
        int bytesRead = read(0, nameBuf, sizeof(nameBuf)); //bytesRead variable to know the num of bytes read into nameBuf

        if( !strncmp(nameBuf, "end", 3) )
        {
                printf("end input\n");
                break;
        }
        write(fd, nameBuf,bytesRead); // write bytes read to fd
   }

   FILE* fp = fdopen(fd, "w");
   rewind(fp); // to go back to start of file, so that you can read entire file

 //  close(fd); ---> second option close fd and again open so that file pointer goes to start of file 
 //  fd=open("name.txt", O_RDWR|O_CREAT, 0744);
   printf("FILE Contents are as follows\n");

   while(read(fd,nameBuf,sizeof(nameBuf)) > 0)
   {
        fprintf(stdout, nameBuf); // or use write    
   }

   puts("Operation completed...");

   close(fd);
   return 0;
}

答案 1 :(得分:0)

在&#34;结束输入&#34;之后打印输出。你可以改变代码

while(1)
   {
        puts("Enter name(end to quit) : ");
        read(0, nameBuf, sizeof(nameBuf));

        if( !strncmp(nameBuf, "end", 3) )
        {
                printf("end input\n");
                break;
        }
        write(fd, nameBuf, 7);
    }

 printf("for loop begins...\n");
   for(i=0; i<3; i++)
   {
        fprintf(stdout, nameBuf);
    }

while(1)
   {
        puts("Enter name(end to quit) : ");
        read(0, nameBuf, sizeof(nameBuf));

        if( !strncmp(nameBuf, "end", 3) )
        {
                printf("end input\n");
                break;
        }
        write(fd, nameBuf, 7);
    }


system("cat name.txt");

system()将运行cat以在name.txt输入后显示end的内容。
如果不使用system(),那么你应该从文件中读取然后写入输出。不直接写入nameBuf的内容,这将是最后一次读取输入而不是完整文件内容。所以你从文件中读取然后写入显示 您可以使用此代码

从文件中读取
while ((read(fd, nameBuf, sizeof(nameBuf))) > 0)
{
    write(1, nameBuf, sizeof(nameBuf));
}