hey i want to access a variable value in another file .(without usage of extern and separate header file) . can i do it using fscanf ?? if so then how???

Member Avatar for Mouche

You just need to open a file using fopen(), read in data using fgets() or fscanf(), and then close the file using fclose().

Here is a snippet showing how to read data from a file line by line:
Reading a File Line By Line

If you want to read in numerical values, you need use fscanf().

Here's part of an example of reading in 20 integers line by line into an array:

int fd;
int numbers[20];
int i = 0;
// Open file here using fd

while (fscanf(fd, "%d", &numbers[i]) != EOF) {
  printf("numbers[%d] = %d\n", i, numbers[i]);
  i++;
}

// Close file

Note: I don't use any error checking here. This only works if the file has integers separated by whitespace (spaces or newlines). You will want to check the return value of fscanf(). If it returns 0, then no match occurred. If you put an 'a' in the file of integers, fscanf() would continually fail to match and the program would be stuck in an infinite loop.

Also, you would want to make sure your buffer is large enough to hold all the data in the file. Perhaps you would want to stop reading once you reach your buffer size.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.