简体   繁体   English

C-使用文本文件

[英]C - working with Text Files

Basically, I'm working on a small program in C (again, not a homework task, just some experimentation while I'm away from Uni :) ). 基本上,我正在用C编写一个小程序(再次,这不是一项家庭作业,仅当我离开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. 我的目标是获取一个包含许多单词的文件,这些单词全部用空格分隔,循环遍历该文件,并且每当找到空格时,都将其替换为\\ 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;
}

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? 到目前为止,我已经很基本了,接下来需要做的是拿出论点并将其放入myFile数组中,以便可以将其用作fopen,或者也许有另一种方法可以做到这一点?

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. 除此之外,我的想法是通过fgets将一行读取到一个数组中,逐个字符地遍历char,搜索'',如果找到它,则替换\\ n,然后将该行重写到文件中。 Does this sound sensible, doable? 这听起来明智,可行吗?

Regards, 问候,

and Thanks! 谢谢!

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 并使用fgetc从fpIn逐字节读取,并使用fputc写入新文件

before writing check if the byte is a space (use isspace() ), write a '\\n' instead. 在写之前检查字节是否为空格(使用isspace() ),而不是写一个'\\ n'。

then delete original and rename tmp.out to argv[1] 然后删除原始文件并将tmp.out重命名为argv[1]

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). 这几乎完全是K&R练习1-12要求您执行的操作(如果要跳过文件指针,可以交替将输入文件重定向到标准输入)。 It's a good exercise. 这是一个很好的锻炼。

FYI, a good resource for K&R solutions: http://clc-wiki.net/wiki/K&R2_solutions 仅供参考,K&R解决方案的好资源: http : //clc-wiki.net/wiki/K&R2_solutions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM