程序在多文件情况下运行,提示段错误.但是把所有代码放在一个文件中运行正确
各位前辈,本人刚学习linux系统下编程.现在遇到这样一个疑问,把所有代码放在main函数中编译运行,一切正常.但是,如果把代码分放在不同的C文件中,编译正确,执行时终端提示"段错误".我把代码贴出来,实现一个简单的功能,将一个文件的内容拷贝到另一个文件中,请大家帮我看看,问题出在哪里?
下面是所有代码都在main函数中的情况:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *in, *out;
char ch;
if(argc != 3)
{
printf("Yon forgot to enter a filename. \n");
exit(1);
}
if((in = fopen(argv[1], "rb")) == NULL)
{
printf("Can not open source file.\n");
exit(1);
}
if((out = fopen(argv[2],"wb")) == NULL)
{
printf("Can not open distination file.\n");
exit(1);
}
while(!feof(in))
{
ch = getc(in);
if(!feof(in))
putc(ch,out);
}
fclose(in);
fclose(out);
return 0;
}
在终端中运行命令:
[user@local host user]$ gcc workspace/copyfile/main.c
[user@local host user]$ ./a.out tsee aaa
文件能够正常生成.
下面是分成多文件的情况:
/*******main.c*************/
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
#include "GetAndPut.h"
int main(int argc, char *argv[])
{
FILE *in, *out;
char ch;
if(argc != 3)
{
printf("Yon forgot to enter a filename,\n");
exit(1);
}
Openfile(argv[1], "rb");
Openfile(argv[2], "wb");
while(!feof(in))
{
ch = GetCharFromFile(in);
if(!feof(in))
PutCharToFile(ch, out);
}
fclose(in);
fclose(out);
return 0;
}
/***********file.h*****************/
FILE * Openfile(const char *strFileName, const char *mode);
/***********file.c*****************/
#include <stdio.h>
#include "file.h"
FILE * Openfile(const char *strFileName, const char *mode)
{
FILE * fp;
if((fp = fopen(strFileName, mode)) == NULL)
{
printf("Can not open distination file.\n");
//printf("open failed ! %s", strFileName);
exit(1);
}
return fp;
}
/***********GetAndPut.h*****************/
char GetCharFromFile(FILE *fp);
int PutCharToFile(char chTemp, FILE *fp);
/***********GetAndPut.c*****************/
#include"stdio.h"
char GetCharFromFile(FILE *fp)
{
char chTemp;
chTemp = getc(fp);
return chTemp;
}
int PutCharToFile(char chTemp, FILE *fp)
{
int nReturn;
putc(chTemp, fp);
return nReturn;
}
在终端运行命令:
[user@local host user]$ gcc workspace/copyfile/main.c workspace/copyfile/file.c workspace/copyfile/GetAndPut.c
[user@local host user]$ ./a.out tsee bbbbb
段错误
[user@local host user]$