I have a cipher text file whic开发者_开发百科h has number of values which looks like: number1: {n1,n2,...}% number2: {n1,n2,...} and so on. I want to read this file in C. Then extract n1, n2 till } is reached.any idea how to do it?
If this sample file is in the correct format:
1: {2,3,4}% 5: {6,7,8}
Then you may extract the numbers using the following code:
#include <stdio.h>
int main(int argc, char* argv[])
{
char filename[] = "filename.txt";
FILE *file;
int n, num1, num2;
file = fopen(filename, "r");
while (fscanf(file, "%d: {%d", &num1, &num2) == 2)
{
printf("%d: ", num1);
printf("%d", num2);
while(fscanf(file, ",%d", &num2) > 0)
{
printf(", %d", num2);
}
fscanf(file, "}%% ");
printf("\n");
}
fclose(file);
}
The variable num1
holds the the numbers in front of the {}
, e.g. number1
, number2
, ..., while num2
holds the numbers inside the {}
, e.g. n1
, n2
, ...
The corresponding output for the sample file given above would be:
1: 2, 3, 4
5: 6, 7, 8
精彩评论