0

How do I read each line of a file opened in my C program to an integer array. I cannot use fgets and sscanf as the input is not known beforehand. The length of each row and the number of columns can vary.

Tried fscanf, fgetc, and others, but they seem to run into problems while detecting the newline. And I ended up reading the entire file together, instead of into different arrays.

e.g., the file contains:

1 2 3 4 5

1 2 3

2 3 4

This should be stored in arr1[] = {1,2,3,4,5} , arr2[] = {1,2,3} , arr3[] = {2,3,4}

3
  • 4
    Is this a question about homework? Commented Sep 1, 2011 at 10:53
  • 2
    What was the code you tried with fscanf and fgetc? Commented Sep 1, 2011 at 10:56
  • Nope not homework :) Was messing about with Judy arrays and was trying something out. Commented Sep 1, 2011 at 11:11

1 Answer 1

2

Feed characters into a per-line buffer. Upon end-of-line (i.e., when you hit a newline character \n), tokenize the buffer with strtok or similar. Read the tokens into a pre-allocated or resizable array or struct of your choice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.