我试图建立一个字符串时得到一个换class

我试图构建一个字符串来调用带有args的脚本,其中一个args是从文件中读取但是我得到了一个换档,输出就像这样

/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh xogs1a 3/37 > lastConfig.txt 

我希望3/37和> lastConfig在同一条线上。

这是我的代码。

 char getConfig[100] = "/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh "; char filedumpto[50] = " > lastConfig.txt"; FILE* file = fopen("rport.txt","r"); if(file == NULL) { return NULL; } fseek(file, 0, SEEK_END); long int size = ftell(file); rewind(file); char* port = calloc(size, 1); fread(port,1,size,file); strcat(getConfig, argv[1]); strcat(getConfig, port); strcat(getConfig, filedumpto); printf(getConfig); //system(getConfig); return 0; 

编辑

我将输出转储到一个文件并在vim中打开它以查看它并在变量后发送^ M,这是我相信的输入? 为什么这样做iv尝试了这个post下的解决方案,但它不起作用。

 tester port print!!!! /home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh randa1ar2 5/48^M > SisteConfig.txt tester port print!!!! 

该文件可能以行尾序列结束。

邋,脆弱的解决方案:

 fread(port, 1,size-1, file); // If it's just a CR or LF fread(port, 1,size-2, file); // If it's a combination of CRLF. // your code continues here 

更好的便携式解决方案将执行以下操作:

 char *port = calloc(size+1, sizeof(char)); // Ensure string will end with null int len = fread(port, 1, size, file); // Read len characters char *end = port + len - 1; // Last char from the file // If the last char is a CR or LF, shorten the string. while (end >= p) && ((*end == '\r') || (*end == '\n')) { *(end--) = '\0'; } 

这是工作代码:

 #include  #include  #include  char getConfig[100] = "/home/glennwiz/develop/c/SnuPort/ExpGetConfig.sh "; const char *filedumpto = " > lastConfig.txt"; int main(char argc, char *argv[]) { FILE *file = fopen("rport.txt", "r"); if (file == NULL) { return 1; } fseek(file, 0, SEEK_END); long int size = ftell(file); rewind(file); char *port = calloc(size+1, 1); int len = fread(port, 1, size, file); // Read len characters char *end = port + len - 1; // Last char from the file // While the last char is a CR or LF, shorten the string. while ((end >= port) && ((*end == '\r') || (*end == '\n'))) { *(end--) = '\0'; } strcat(getConfig, argv[1]); strcat(getConfig, port); strcat(getConfig, filedumpto); printf("%s\n", getConfig); return 0; } 

输入文件( "rport.txt" )可能包含换行符。 从读取输入的末尾剥去空白,应该没问题。