#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char sharePath[100];
char logPath[100];
char motd[100];
}pathName_t;
void readConfig(const char *config){
FILE *fp = fopen(config, "r");
pathName_t pathpath;
int line = 0;
int index = 0;
int c;
c = getc(fp);
while( c != EOF){
if( c != '\n' ){ //if c not equal to new line, loop through the entire line
if( line == 0 ){ //line = 0
pathpath.sharePath[index] = c;
}else if( line == 1 ){ //line = 1
pathpath.logPath[index] = c;
}else{ //line = 2
pathpath.motd[index] = c;
}
index++;
}else{ //if c equal to new line, replace \0 from \n to the end of string
if( line == 0 ){ //line = 0
pathpath.sharePath[index] = '\0';
}else if( line == 1 ){ //line = 1
pathpath.logPath[index] = '\0';
}else{ //line = 2
pathpath.motd[index] = '\0';
}
index = 0;
line++;
} // else close
c = getc(fp);
} //while loop close
fclose(fp);
} //readConfig() close
int main(){
pathName_t pathName;
readConfig("settings.config");
printf("%s", pathName.motd);
printf("%s",pathName.sharePath);
}
这是我得到的结果:�z���
我打算创建一个函数来读取和检索多行存储在该文件中的路径名,最终编译了结构,但结果似乎出错了。或者你们中的任何人有建议是否还有其他方法可以从文件中读取内容并有多个返回值?
最佳答案
你的函数什么也不做。您不将指针传递给局部变量或为其分配返回值,并且打印堆栈上的随机垃圾
关于c - 结构函数返回垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56481933/