Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        5年前关闭。
                                                                                            
                
        
在C语言中,我想从文件中读取许多符号,对于每2个符号,我想将其反转。例如,如果输入为:abcdef,我希望输出为:badcfe。

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>

FILE *f,*g;

int main(int argc,char *argv[])
{
    if((f=open(argv[1],O_RDONLY))==NULL)
    {
        fprintf(stderr,"Open file error: %s\n",argv[1]);
        return 1;
    }

    if((g=open(argv[2],O_WRONLY|O_TRUNC|O_CREAT,O_RDWR))==NULL)
    {
        fprintf(stderr,"Open file error: %s\n",argv[2]);
        fclose(f);
        return 1;
    }

    int nr;
    char *buffer;
    buffer=(char *)malloc(sizeof(char));
    char *bufferOut=buffer;

    while((nr=read(f,buffer,2*sizeof(char))>0)){
        bufferOut[1]=buffer[0];

        bufferOut[0]=buffer[1];
        if(write(g,bufferOut,2*sizeof(char))!=2*sizeof(char)){
            printf("Writing ERROR!");
            return 1;
        }
    }
    close(f);
    close(g);
    return 0;
}


打开g后执行后,内容为:aaccee

我在linux上。

最佳答案

我认为您的问题出在以下几行代码中:

bufferOut[1]=buffer[0];

bufferOut[0]=buffer[1];


根据这些行,bufferOut和buffer指向相同的内存区域:

char *buffer;
buffer=(char *)malloc(sizeof(char));
char *bufferOut=buffer;


这不执行所需的交换。由于bufferOut和buffer指向相同的内存区域,因此您要将bufferOut [0]和bufferOut [1]分配给相同的值。尝试将bufferOut [1]的原始内容存储在一个临时变量中,然后将其分配给bufferOut [0]。

10-07 12:59