代码:
#include "stdafx.h"
#include
#include
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;
}
你开的内存空间太大,写入 的内容太少。
我初步试了一下,这个问题是出在了fgetc()这个函数里面,因为里面的参数是一个文件流,所以出现了屯屯这种字符串。你把while ((ch = fgetc(fp) != EOF))
{
cout << ch;
}
cout << endl;这些注释掉 试一下
我改了一下
FILE *fp = fopen("D:\test.txt", "w");
if (fp == NULL)
{
return 0;
fclose(fp);
}
fputs("Hello,world!\n", fp);
fputs("Hello,UESTC!\n", fp);
fclose(fp);
cout << "文件内容:" << endl;
fp=fopen("D:\test.txt", "r");
while ((ch = fgetc(fp) != EOF))
{
cout << ch;
}
cout << endl;
fclose(fp);
原因是你fopen的权限是能写的,那么他就把文件流全写进去了,不过这样改出来的在控制台上打印的是乱码我再看看怎么改
fgetc返回的是一个数字,也就是说ASNI编码的数字,你打印的时候还是用printf吧,printf("%c,"ch);
源码修改为int ch;
// winT.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//#include
#include
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("D:\test.txt", "w");
if (fp == NULL)
{
return 0;
fclose(fp);
}
fputs("Hello,world!\n", fp);
fputs("Hello,UESTC!\n", fp);
fclose(fp);
cout << "文件内容:" << endl;
fp=fopen("D:\test.txt", "r");
//int i = fgetc(fp);
int i;
//printf("%c",i);
//cout<<i<<endl;
while((i = fgetc(fp)) != EOF)
{
printf("%c", i);
}
fclose(fp);
//cout << endl;
FILE *testfp = fopen("D:\\test.txt", "r");
ReadALine(buf, 20, testfp);
cout << buf;
cout << endl;
fclose(testfp);
system("PAUSE");
return 0;
}
你把char ch改成int ch