C - 处理文本文件

发布于 2024-12-22 20:14:04 字数 603 浏览 5 评论 0原文

基本上,我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

定格我的天空 2024-12-29 20:14:04

最简单的方法是以二进制模式打开文件

FILE *fpIn = fopen( argv[1], "rb" );

,然后打开一个新文件进行写入

FILE* fpOut =  fopen( "tmp.out", "wb" );

,并使用 fgetc 并使用 fputc 编写 在写入之前检查新文件

是否为空格(使用 isspace()),写入 '\n' 代替。

然后删除原始并将 tmp.out 重命名为 argv[1]

the simplest way is to open the file in binary mode

FILE *fpIn = fopen( argv[1], "rb" );

then open a new file for writing

FILE* fpOut =  fopen( "tmp.out", "wb" );

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 to argv[1]

九八野马 2024-12-29 20:14:04

这几乎正​​是 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文