C - 处理文本文件
基本上,我正在用 C 编写一个小程序(同样,这不是一项家庭作业,只是我离开大学时的一些实验:))。我的目标是获取一个包含大量单词的文件,所有单词均由空格分隔,循环遍历该文件,每当找到空格时,将其替换为 \n ,从而创建一个大的单词列表。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
char myFile[100];
int i;
FILE *file;
while(argc--) {
printf("%s\n", *argv++);
}
return 0;
}
到目前为止,我所拥有的非常基本,接下来我需要做的是接受争论并将其敲入 myFile 数组中,以便我可以将其用作 fopen,或者也许还有另一种方法可以做到这一点?
除此之外,我的想法是通过 fgets 读取一行,放入数组中,逐个字符地循环遍历它,搜索 ' ',如果找到它,则替换为 \n,然后将该行重写到文件中。这听起来明智、可行吗?
问候,
谢谢!
Basically, I'm working on a small program in C (again, not a homework task, just some experimentation while I'm away from Uni :) ). My goal is to take a file containing lots of words all seperated by spaces, loop through the file, and whenever a space is found, replace that for a \n thus creating a large list of words.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
char myFile[100];
int i;
FILE *file;
while(argc--) {
printf("%s\n", *argv++);
}
return 0;
}
Very basic what I have so far, what I need to do next is to take the arguement and whack it in the myFile array, so that I can use that as the fopen, or maybe there is another way to do this?
Beyond that, my idea was to then read a line, into an array via fgets, loop through it char by char, searching for ' ', if I find it, replace is for \n, then rewrite that line to the file. Does this sound sensible, doable?
Regards,
and Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是以二进制模式打开文件
,然后打开一个新文件进行写入
,并使用 fgetc 并使用 fputc 编写 在写入之前检查新文件
是否为空格(使用
isspace()
),写入 '\n' 代替。然后删除原始并将
tmp.out
重命名为argv[1]
the simplest way is to open the file in binary mode
then open a new file for writing
and read byte by byte from fpIn using fgetc and write using fputc to the new file
before writing check if the byte is a space (use
isspace()
), write a '\n' instead.then delete original and rename
tmp.out
toargv[1]
这几乎正是 K&R 练习 1-12 要求您做的事情(如果您想跳过文件指针,您可以将输入文件交替重定向到标准输入)。这是一个很好的练习。
仅供参考,K&R 解决方案的良好资源:
http://clc-wiki.net/wiki/K&R2_solutions
This is pretty much exactly what K&R Exercise 1-12 asks you to do (you could redirect the input file to standard input alternately, if you want to skip the file pointers). It's a good exercise.
FYI, a good resource for K&R solutions:
http://clc-wiki.net/wiki/K&R2_solutions