C语言把文件读入字符串以及将字符串写入文件

1.纯C实现

 FILE *fp;
	if ((fp = fopen("example.txt", "rb")) == NULL)
	{
		exit(0);
	}
	fseek(fp, 0, SEEK_END);
	int fileLen = ftell(fp);
	char *tmp = (char *) malloc(sizeof(char) * fileLen);
	fseek(fp, 0, SEEK_SET);
	fread(tmp, fileLen, sizeof(char), fp);
	fclose(fp);
	for(int i = 0; i < fileLen; ++i)
	{
		printf("%d  ", tmp[i]);
	}
	printf("\n");
 
	if ((fp = fopen("example.txt", "wb")) == NULL)
	{
		exit(0);
	}
	rewind(fp);
	fwrite(tmp, fileLen, sizeof(char), fp);
	fclose(fp);
	free(tmp);

2.利用CFile(MFC基类)

CFile需要包含的头文件为Afx.h

打开文件的函数原型如下

if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))

有多种模式,常用的有如下:

modeRead

modeWrite

modeReadWrite

modeCreate

文件类型有两种:

typeBinary

typeText

读写非文本文件一定要用typeBinary

读取数据的函数原型:

virtual UINTRead(void*lpbuf, UINT nCount);

将文件读出:

CFile fp;
if(!(fp.Open((LPCTSTR)m_strsendFilePathName,CFile::modeRead)))
{
    return;
}
fp.SeekToEnd();
unsignedint fpLength = fp.GetLength();
char *tmp= new char[fpLength];
fp.SeekToBegin();    //这一句必不可少
if(fp.Read(tmp,fpLength) < 1)
{
    fp.Close();
    return;
}

// 新建文件并写入

if(!(fp.Open((LPCTSTR)m_strsendFilePathName, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary)))
{
    return;
}
fp.SeekToBegin();
fp.write(tmp,fpLength);
fp.close;
C语言中,你可以通过以下几个步骤完成这个任务: 1. 首先,需要包含头文件`stdio.h`用于文件操作,以及`ctype.h`用于处理字符的大小转换。 ```c #include <stdio.h> #include <ctype.h> ``` 2. 使用`fgets()`函数从键盘读取一行字符串到`str`数组中,并追加`\0`结束符。 ```c char str[100]; fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; // 移除行尾的换行符 ``` 3. 创建一个新字符串`result`,用于存储大小字母互换后的字符串。 ```c char result[strlen(str) + 1]; // 确保足够的空间 ``` 4. 使用`tolower()`和`toupper()`函数遍历输入字符串,交换大小字母。 ```c for (int i = 0; str[i] != '\0'; i++) { if (isalpha(str[i])) { // 检查是否为字母 result[i] = islower(str[i]) ? toupper(str[i]) : tolower(str[i]); // 互换大小 } else { result[i] = str[i]; // 其他非字母字符不变 } } result[strlen(str)] = '\0'; // 结束字符串 ``` 5. 将互换后的字符串写入文件`1.txt`的第二行。这里假设已经创建了文件指针`file`。 ```c fprintf(file, "%s\n", result); // 写入文件 ``` 6. 最后,将互换后的字符串打印到屏幕上。 ```c printf("After swapping: %s\n", result); ``` 7. 关闭文件指针并关闭文件(如果之前打开过的话),这里是完整的代码片段: ```c #include <stdio.h> #include <ctype.h> int main() { char str[100]; FILE *file = fopen("1.txt", "a+"); // 打开文件(如果不存在会自动创建) fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; char result[strlen(str) + 1]; for (int i = 0; str[i] != '\0'; i++) { if (isalpha(str[i])) { result[i] = islower(str[i]) ? toupper(str[i]) : tolower(str[i]); } else { result[i] = str[i]; } } result[strlen(str)] = '\0'; fprintf(file, "%s\n", result); printf("After swapping: %s\n", result); fclose(file); // 关闭文件 return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值