c语言写入txt没事,但读刚刚写入的txt,却显示为乱码
#include<stdio.h>#include<string.h>#include<stdlib.h>#defineLENGTH81#defineBUFSIZE102...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define LENGTH 81
#define BUFSIZE 1024
int main()
{
FILE*pfile = nullptr;
char*filename = "1.txt";
char mystr[LENGTH];
int mychar = 0;
if (!fgets(mystr, LENGTH, stdin))
{
printf_s("Input from keyboard failed.\n");
exit(1);
}
if (fopen_s(&pfile, filename, "w"))
{
printf("Error opening %s for writing.program terminated.\n", filename);
exit(1);
}
setvbuf(pfile, nullptr, _IOFBF, BUFSIZE);
for (int i = strnlen_s(mystr, LENGTH) - 1; i >= 0; --i)
fputc(mystr[i], pfile);
fclose(pfile);
if (fopen_s(&pfile, filename, "r"))
{
printf("Error opening %s for writing.program terminated.\n", filename);
exit(1);
}
setvbuf(pfile, nullptr, _IOFBF, BUFSIZE);
printf_s("the data read from file is:\n");
while (mychar = fgetc(pfile) != EOF)
putchar(mychar);
putchar('\n');
fclose(pfile);
pfile = nullptr;
system("pause");
} 展开
#include<string.h>
#include<stdlib.h>
#define LENGTH 81
#define BUFSIZE 1024
int main()
{
FILE*pfile = nullptr;
char*filename = "1.txt";
char mystr[LENGTH];
int mychar = 0;
if (!fgets(mystr, LENGTH, stdin))
{
printf_s("Input from keyboard failed.\n");
exit(1);
}
if (fopen_s(&pfile, filename, "w"))
{
printf("Error opening %s for writing.program terminated.\n", filename);
exit(1);
}
setvbuf(pfile, nullptr, _IOFBF, BUFSIZE);
for (int i = strnlen_s(mystr, LENGTH) - 1; i >= 0; --i)
fputc(mystr[i], pfile);
fclose(pfile);
if (fopen_s(&pfile, filename, "r"))
{
printf("Error opening %s for writing.program terminated.\n", filename);
exit(1);
}
setvbuf(pfile, nullptr, _IOFBF, BUFSIZE);
printf_s("the data read from file is:\n");
while (mychar = fgetc(pfile) != EOF)
putchar(mychar);
putchar('\n');
fclose(pfile);
pfile = nullptr;
system("pause");
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询