c 用fopen函数以w模式打开,再fputs写了两句话,但多打印出很多“屯”?

// ReadALine.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

#include <iostream>

#include <stdio.h>

using namespace std;

char *ReadALine(char *buf, int n, FILE *fp)

{

char ch;

int i = 0;

ch = fgetc(fp);

while (ch != EOF)

{

if ((ch == '\n') || (ch == '\r'))

{

buf[i++] = '\0';

break;

}

else if (i == n - 1)

{

buf[i] = '\0';

break;

}

else

{

buf[i++] = ch;

}

}

return buf;

}

int _tmain(int argc, _TCHAR* argv[])

{

char buf[30];

memset(buf, 0, sizeof(buf));

char ch;

FILE *fp = fopen("C:\\test.txt", "w");

if (fp == NULL)

{

return 0;

fclose(fp);

}

fputs("Hello,world!\n", fp);

fputs("Hello,UESTC!\n", fp);

cout << "文件内容:" << endl;

while ((ch = fgetc(fp) != EOF))

{

cout << ch;

}

cout << endl;

fclose(fp);

FILE *testfp = fopen("C:\\test.txt", "r");

ReadALine(buf, 20, testfp);

cout << buf;

cout << endl;

fclose(testfp);

system("pause");

return 0;

}

图片描述

回答:

FILE *fp = fopen("C:\\test.txt", "w");

while ((ch = fgetc(fp) != EOF))

{

cout << ch;

}

你用 w 模式读取文件内容,错了吧~

以上是 c 用fopen函数以w模式打开,再fputs写了两句话,但多打印出很多“屯”? 的全部内容, 来源链接: utcz.com/p/195094.html

回到顶部