c - 如何在 C 控制台程序中读取 .txt 文件?
问题描述
我有一个程序,我必须从用户输入中读取数据对列表,例如:
1,2 3,4 5,6
或者:
1,2
3,4
5,6
4,3
这是我的代码
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; ++i)
printf("%d ", arr[i]);
}
int main()
{
int n1, n2;
int x[10] = { 0 };
int y[10] = { 0 };
int capacity = 0;
int n = sizeof(x) / sizeof(x[0]);
for (size_t i = 0; i < n; ++i)
{
scanf_s(" %d , %d [^\n]", &n1, &n2);
x[i] = n1;
y[i] = n2;
}
for (int j = 0; j < n; ++j)
{
printf("%d , %d\n", x[j], y[j]);
}
quickSort(x, 0, n-1);
printArray(x, n);
printf("Minimum is: %d", x[0]);
printf("Maximum is: %d", x[n-1]);
return 0;
}
但是,当我尝试通过在 CMD 中运行命令将文件传输到控制台时:program.exe some.txt
它会给我:
-858993460 , -858993460
-858993460 , -858993460
...
但是当我输入 txt 文件中的值时,我得到了正确的输出。
无论如何让 C 控制台程序接受用户输入和 .txt 文件?
我的教授展示了一个使用 scanf_s 的示例,他可以只使用 debug.exe 和 txt 文件来获取输入,他说这会诱使程序认为它来自键盘缓冲区。我对这将如何工作感到困惑。
来自 CMD 的错误代码:
C:\Users\username\Downloads\Project\test_files>sort.exe book.txt -> sort.exe < book.txt
该进程无法访问该文件,因为它正被另一个进程使用。
另一个错误是一个红色的弹出窗口,说我应该得到一个最终版本(它是从窗口弹出的)。
解决方案
你的命令行是错误的。
代替:
sort.exe < book.txt -> sort.exe < book.txt
你要:
sort.exe < book.txt | sort.exe > book2.txt
但无论如何,我不确定你到底想在这里做什么......
请注意,您需要其他文件book2.txt
而不是,这就是错误book.txt
的原因。The process cannot access the file because it is being used by another process.
推荐阅读
- firebase - devtools 2.3.2 包的问题 - 找不到包
- python - 图片未加载到网页
- javascript - 向上缩放 y 轴,同时使用 D3.js 向下缩放 x 轴
- dart - 如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?
- python - ttk 图像按钮仅显示集合中最后一个项目的图像
- javascript - 为什么javascript在正则表达式上抛出错误
- react-native - 反应原生 GeoFencing geolib 库
- sql - Oracle 合同模块中的 Oracle“付款期限天数”列。(Oracle 电子商务套件 12.1.3 版)
- pandas - Matplot 删除两个单独的日期时间点之间的空格
- javascript - Angular JS 在 jquery 之后不起作用。执行加载函数