所以我有一个方法将字符串从文件移动到c中的char数组,但是当我尝试将其打印出来时,我在终端中得到一个奇怪的输出,看起来像是每个char点的一堆每个方框都有4个0和1个。
这是我的代码:
int main(int argc, char** argv){
if(argc != 3){
printf("not valid # of arguments");
return 1;
}
struct stat info;
int status;
status = stat(argv[2], &info);
if(status != 0){
printf("Error, errno = %d\n", errno);
return 1;
}
//command line argument is file
if(S_ISREG (info.st_mode)){
printf("%s is a file \n", argv[2]);
char *string1;
string1 = getFileString(argv[2]);
printf("string in file is %s \n", string1);
free(string1);
return 0;
}
if(S_ISDIR(info.st_mode)){
printf("%s is a directory \n", argv[2]);
openDirRec(argv[2]);
//what to do if command line argument is directory
}
return 0;
}
char* getFileString(char *fileName){
FILE* qp;
qp = fopen(fileName, "r");
char ch;
struct stat st;
if(stat(fileName, &st) != 0) {
return NULL;
}
/*int sizeCheck = 0;
while((ch=fgetc(qp))!=EOF){
sizeCheck++;
}
*/
int sizeCheck = st.st_size;
if(sizeCheck == 0){
return NULL;
}
else{
//fseek(qp, SEEK_SET, 0);
char *fileString;
fileString = (char*)malloc(sizeof(char) * sizeCheck + 1);
memset(fileString, 0, sizeCheck + 1);
//rewind(qp);
int count = 0;
while((ch=fgetc(qp)!=EOF)){
fileString[count] = ch;
count++;
}
printf("%s\n", fileString);
fileString[sizeCheck] = '\0';
fclose(qp);
return fileString;
}
}
答案 0 :(得分:2)
这条线是罪魁祸首。
while((ch=fgetc(qp)!=EOF))
由于运算符优先级,这相当于:
while(ch = (fgetc(qp)!=EOF) )
你需要的是对parantheses的一点重新安排。
while((ch=fgetc(qp)) != EOF)