I have a text file of 4 rows 3 columns ex:
1 2 5
3 5 6
8 8 2
1 1 0
I want to move from one file to the other file the third column so the new text will look like this
5
6
2
0
I've done this with fscanf so that every third time I use fscanf to insert it to the new file Is there a better way to access the third column other that scanning the first 2 numbers? Thanks
CodePudding user response:
*scanf
is far more complex than you need for something this simple. When you can avoid scanf
, you should. (You can almost always avoid it, where "almost" is just me hedging). This is a simple task, which should be done with simple tools. For example:
#include <ctype.h>
#include <stdio.h>
/* A simple implementation of `awk '{print $3}'` */
int
main(int argc, char* argv[])
{
int c;
int column = 0;
int last = ' ';
while( (c = getchar()) != EOF ){
if( ! isspace(c) && isspace(last)){
column = 1;
}
if( c == '\n' ){
column = 0;
putchar(c);
} else if( column == 3 ){
putchar(c);
}
last = c;
}
}
CodePudding user response:
Oh, I see. This worked for me.
#include <stdio.h>
#include <string.h>
int main() {
char line[25];
FILE * file;
file = fopen("text1.txt", "r");
fscanf(file, "%[^\n]s", &line);
printf("%s", line strlen(line) - 1);
fclose(file);
return 0;
}
Basically, you will store an entire line in an array of chars, then you will print certain pieces of that string (array of chars). With that in mind, you can make a way to do with multiple lines.
Hope this helped you out.