c - Visual Studio 文件输出错误

标签 c eclipse visual-studio-express

当我在 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/

相关文章:

c - 无法从函数返回 char 指针

java - 在eclipse中远程调试Hadoop

c# - 在 .NET 中使用 Microsoft.Office.Interop.Excel 需要哪些引用资料?

C++ Visual Studio Express 2010 无法启动程序报错

c# - 在 Visual Studio Express 中开发 Silverlight?

c++ - C++ 和 C 中指针和数组的区别

c - 将 Arduino 与 MATLAB 连接进行图像处理

android - 无法在Android Studio中运行项目。也许是因为gradle?

c - 在 C 中使用 GoString

eclipse - 在 Eclipse CDT 中将项目类型从 "Executable"更改为 "Static Library"