1

我有这段代码,我在读取系统调用时遇到了 BAD FILE DESCRIPTOR 问题。但是,我使用相同文件描述符的写调用工作正常。请建议

    void Update_Log( )
{
        struct logDetails update,update1[30];
        struct stat fileData,fileData1;
        int file;
        int index;
        //pthread_t pid;
        char writeBuffer[MAX_BUFFER_SIZE];
        char readBuffer[MAX_BUFFER_SIZE];
        char mBuf[MAX_BUFFER_SIZE],mBuf1[MAX_BUFFER_SIZE];
        if((access("/home/team02/DMS/Server/",F_OK))==0) //checking the file/dir existence
                puts("file found");
        else
                puts("file not found");
        if((file=open("/home/team02/DMS/Server/filename.txt",O_RDONLY|O_WRONLY|O_APPEND,S_IRWXU))==-1)
                perror("file not opened");
        if((fstat(file, &fileData))==-1)
                perror("structure not filled");
        if((stat("/home/team02/DMS/Server/f1",&fileData1))==-1)
                perror("structure not filled");

        //printf("%d/n",fileData.st_mtime);
        //printf("%d",fileData.st_ctime);
        struct tm *mytm = localtime(&fileData.st_mtime);
        struct tm *mytime=localtime(&fileData1.st_mtime);
        strftime(mBuf1,18,"%I:%M:%S-%m%d%y",mytime);
        strftime(mBuf, 18, "%I:%M:%S-%m/%d/%y", mytm);
        puts(mBuf);
        if((strcmp(mBuf,mBuf1)==0))
                puts("equal");
                                else
                puts("not equal");
        strcpy(update.timestamp,mBuf);
        strcpy(update.clientName,mBuf);
        strcpy(update.filename,mBuf1);
        snprintf(writeBuffer,MAX_BUFFER_SIZE,"%s %s %s",update.clientName,update.filename,update.timestamp);
        //printf("%s",writeBuffer);
        //if((pthread_create(&pid,&thread_handler,NULL))!=0)
                //perror("Thread not created");
        if((write(file,writeBuffer,strlen(writeBuffer)))==-1)
                perror("write unsuccessful");
        **if((read(file,readBuffer,MAX_BUFFER_SIZE))==-1)
                perror("read unsuccessful");**
        for(index=0;index<strlen(readBuffer);index++)
        {
                sscanf(readBuffer,"%s %s %s",update1[index].clientName,update1[index].filename,update1[index].timestamp);
                printf("%s",update1[index].clientName);
        }
        close(file);
}
4

1 回答 1

3

根据运行时库,打开模式O_RDONLY|O_WRONLY可能会出现问题。你可能想O_RDWR更换那部分。

此外,您可以获取errno值以准确找出问题所在。perror()在发生错误的情况下调用。那应该告诉你问题是什么。程序产生什么输出?

于 2012-08-21T05:57:34.600 回答