我正在尝试在Red Hat Linux中模拟cat命令。运行程序时出现分段错误。
例如:
./a.out a > b
a包含你好。我希望 hello 被复制到b.
我的代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[])
{
    int f, fd, r;
    char buf[100];
    if (argc < 2)
    {
        printf("Error");
        return 0;
    }
    else
    {
        if (!strcmp(argv[2],">"))
        {
            f = open(argv[1],0,00777);
            if (f == -1)
                printf("no file");
            else
            {
                fd = creat(argv[3],00777);
                while( (r = read(f,buf,50)) > 0)
                    write(fd, buf, r);
            }
        }
    }
    return 0;
}
为什么我会收到分段错误?
我有一个类似的程序,我在其中以相同的方式打开和创建文件,并且该程序正在运行,但是这个程序给了我一个分段错误。