当我在 eclipse 上构建下面的代码时,命令行上的一切都按预期工作,输出文件中的一切看起来都应该如此。
#include <stdio.h>
#include <stdlib.h> // for exit()
#include <string.h>
int main(int argc, char *argv[])
{
FILE *in, *out; // declare two FILE pointers
int ch;
// check for command-line arguments
if (argc < 2)
{
fprintf(stderr, "Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
// set up input
if ((in = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr, "I couldn't open the file \"%s\"\n",
argv[1]);
exit(EXIT_FAILURE);
}
// set up output
char *ptd;
ptd = (char*)malloc(150 * sizeof(char));
char x;
int i = 0;
while ((x = getchar()) != '\n'){
ptd[i] = x;
i++;
}
ptd[i + 1] = '\0';
strcat(ptd, ".txt"); // append .txt
if ((out = fopen(ptd, "w")) == NULL)
{ // open file for writing
fprintf(stderr, "Can't create output file.\n");
exit(3);
}
// copy data
while ((ch = getc(in)) != EOF)
putc(ch, out); // print every 3rd char
// clean up
if (fclose(in) != 0 || fclose(out) != 0)
fprintf(stderr, "Error in closing files\n");
free(ptd);
return 0;
}
但是当我用 visual studio 构建它时,我在文件名后得到这个东西“Í”,直到它到达 .txt 并且它使用所有分配的内存作为文件名。为什么会这样?
最佳答案
您没有正确终止字符串:
while ((x = getchar()) != '\n'){
ptd[i] = x;
i++;
}
ptd[i + 1] = '\0';
这里 i
在循环中递增,这样最后的 i
已经超过了构建的字符串。因此 ptd[i + 1] = '\0';
行中的额外增量将留下一个未初始化的字符。所以正确的代码应该是 ptd[i] = '\0';
关于c - Visual Studio 文件输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191152/