读取txt文件内容,并按一定长度分页显示

private List<string> SaveContentUpload(FileUpload file)
{
List<string> list_content = new List<string>();//定义集合,存储文件内容
double count = 0;
int pagesize = 1000;//设置每次读取的长度为1000
string context = "";//上传文件内容
using (Stream reader = file.PostedFile.InputStream)
{
int FileLen = file.PostedFile.ContentLength;//获取上传文件的大小
byte[] buff = new byte[FileLen];
reader.Read(buff, 0, FileLen);
reader.Position = 0;
System.IO.StreamReader sr = new System.IO.StreamReader(reader, System.Text.Encoding.Default);
context = sr.ReadToEnd();
count = context.Length;
int num = Convert.ToInt32(Math.Ceiling(count / pagesize));
for (int i = 0; i < num; i++)
{
int sum = pagesize;
if (count - (i * pagesize) < pagesize)
{
sum = Convert.ToInt32(count - (i * pagesize));
}
string text = context.Substring(i * pagesize, sum);
list_content.Add(text);
}
}
return list_content;
}

转载于:https://www.cnblogs.com/www-mcl-1234/p/10858161.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以按照以下步骤来实现: 1. 使用 `mmap` 将二进制文件映射到内存中,返回指向该映射区域的指针。可以使用 `open` 和 `fstat` 函数获取文件的描述符和大小信息。 2. 定义一个字符数组,并分配足够的空间来存储所有的数据。根据题目要求,数组长度应为 128 * 4 = 512。 3. 使用 `fread` 从内存映射区域中读取数据,并将其存储到字符数组中。 4. 遍历字符数组,按题目要求输出数据。 下面是一份示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #define PAGE_SIZE 32 #define ROW_SIZE 8 #define ARRAY_SIZE 128 int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <filename>\n", argv[0]); exit(1); } int fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); exit(1); } struct stat file_stat; if (fstat(fd, &file_stat) < 0) { perror("fstat"); exit(1); } char *data = mmap(NULL, file_stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (data == MAP_FAILED) { perror("mmap"); exit(1); } char array[ARRAY_SIZE * 4]; fread(array, 1, ARRAY_SIZE * 4, fd); for (int page = 0; page < 4; page++) { printf("Page %d:\n", page + 1); for (int row = 0; row < PAGE_SIZE / ROW_SIZE; row++) { for (int col = 0; col < ROW_SIZE; col++) { int index = page * PAGE_SIZE * ARRAY_SIZE + row * ROW_SIZE + col; printf("%c ", array[index]); } printf("\n"); } printf("\n"); } munmap(data, file_stat.st_size); close(fd); return 0; } ``` 在上面的代码中,我们首先打开了指定的文件,并使用 `fstat` 获取了文件的大小信息。然后,我们使用 `mmap` 将文件映射到内存中,并使用 `fread` 从内存中读取数据到字符数组中。 最后,我们遍历字符数组,按照题目要求输出数据。需要注意的是,我们在计算数组中的索引时,考虑了分页和每行元素个数的限制。最后,我们使用 `munmap` 和 `close` 函数释放了资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值