1

引数を使用してスクリプトを呼び出す文字列を作成しようとしていますが、引数の1つがファイルから読み取られますが、ラインシフトが取得され、出力は次のようになります

/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はこの投稿の下で解決策を試しましたが、うまくいきません。

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

2 に答える 2

4

入力ファイル ( "rport.txt") に改行が含まれている可能性があります。読み取り入力の末尾から空白を削除すると、問題ありません。

于 2012-03-09T14:09:39.567 に答える
1

ファイルはおそらく行末シーケンスで終了します。

安っぽい、もろい解決策:

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 <stdio.h>
#include <stdlib.h>
#include <string.h>

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;
}
于 2012-03-09T14:20:05.257 に答える